#!/bin/sh
#
# hdw - linux /etc/init.d/rc (modified for fai)
#
# controls switching of runlevels	(copied from ROCK Linux)
#

exec 2>&1

export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/fai/scripts

echo "** running rc (fai) script **"

echo "RC: Previous runlevel: $PREVLEVEL, current runlevel: $RUNLEVEL."

curdir=/etc/init.d/rc$RUNLEVEL.d
prevdir=/etc/init.d/rc$PREVLEVEL.d

#
# run the KILL scripts of the previous runlevel (if needed)
#
if ! [ $PREVLEVEL = S -o $PREVLEVEL = N ]
then
	echo "RC: Leave runlevel $PREVLEVEL ..."
	for i in $prevdir/K*; do
		test -x "$i" || continue
		x="`echo "$i" | sed "s,$prevdir/K..,$curdir/S??,"`"
		[ "`echo $x`" = "$x" ] || continue ; unset x
		$i stop < /dev/null
	done
fi

echo "RC: Enter runlevel $RUNLEVEL ..."

if [ $RUNLEVEL = S ]
then
	#
	# Kill all processes
	#
	echo "Sending all processes a SIGTERM (15) ..."
	killall5 -15
	sleep 5
	echo "Sending all processes a 2nd SIGTERM (15) ..."
	killall5 -15
	sleep 3
	echo "Sending all processes a SIGKILL (9) ..."
	killall5 -9
	sleep 3
elif [ $RUNLEVEL = 0 -o $RUNLEVEL = 6 ]
then
	#
	# shut down the system
	#
	if [ $RUNLEVEL = 0 ] ; then
	mode=halt ; else mode=reboot ; fi
	/etc/init.d/down $mode
	exit 0
else
	#
	# run the START scripts of the current (new) runlevel
	#
	for i in $curdir/S*; do
		test -x "$i" || continue
		x="`echo "$i" | sed "s,$curdir/S..,$prevdir/K??,"`"
		[ "`echo $x`" = "$x" ] || continue ; unset x
		$i start < /dev/null
	done
fi

echo "mounting fai config space ..."
FAI_MOUNT_LINE
echo "done"

echo "executing rc_fai.sh script ..."
/fai/scripts/rc_fai.sh
echo

if [ -f /tmp/fai_finished ] ; then
	echo
	echo "FAI finished - congrats :)"
	echo
	echo "you may login as root (passwd = hdw), chroot to /trg and"
	echo "do further modifications."
	echo
else
	echo "login: root | passwd = hdw"
fi

exit 0
