Shell script to boot OSX in recovery mode and execute another shellscript
To set the flag to boot in safe mode is the easiest:
sudo nvram boot-args="-x"

The I guess we have to do something with;

rc.boot figures out the type of boot (Multi-User, Safe, CD-ROM, Network etc.). In case of a network boot (the sysctl variable kern.netboot will be set to 1 in which case), it runs /etc/rc.netboot with a start argument.

and this;

/etc/rc finally launches /sbin/SystemStarter to handle startup items from locations such as /System/Library/StartupItems and /Library/StartupItems. A StartupItem is a program, usually a shell script, whose name matches the folder name. The folder contains a property list file containing key-value pairs such as Description, Provides, Requires, OrderPreference, start/stop messages etc. You can run SystemStarter -n -D as root to have the program print debugging and dependency information (without actually running anything).

ref: http://osxbook.com/book/bonus/ancient/whatismacosx/arch_startup.html