#!/bin/sh
#
# dRock Linux: /etc/init.d/rc
# Desc: the script does the switching between runlevels
#
# (C) JUN 2000 by V Ziegler <ziegler@informatik.hu-berlin.de>
#     MAR 2001 by Ren Rebe <rene.rebe@gmx.net> 
#

exec 2>&1

trap "echo" SIGINT

. /etc/init.d/master.sh

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

c_writeln "*** Running rc script ***"
c_write "previous runlevel: "
echo -ne ${stat_message_color}${PREVLEVEL}${message_end_color}
c_write ", current runlevel: "
echo -e  ${stat_message_color}${RUNLEVEL}${message_end_color}

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

failed=""

c_writeln " RC: Leave runlevel $PREVLEVEL "
c_writeln "<----------------------------- "

if [ $PREVLEVEL = S ]
then
	#
	# nothing to do
	#
	:
elif [ $PREVLEVEL = N ]
then
	#
	# run the START scripts in boot.d
	#
	for i in /etc/init.d/boot.d/S*; do
		test -x "$i" || continue
		$i start < /dev/null || failed=$failed" "$(basename $i)
	done
else
	#
	# run the KILL scripts of the previous runlevel
	#
	for i in $prevdir/K*; do
		test -x "$i" || continue
		$i stop < /dev/null
	done
fi

c_writeln " RC: Enter runlevel $RUNLEVEL"
c_writeln "----------------------------->"

if [ $RUNLEVEL = S ]
then
	#
	# Kill all processes
	#
	c_writeln "Sending all processes a SIGTERM (15) ..."
	killall5 -15
	sleep 4
	c_writeln "Sending all processes a 2nd SIGTERM (15) ..."
	killall5 -15
	sleep 1
	c_writeln "Sending all processes a SIGKILL (9) ..."
	killall5 -9
	sleep 2
elif [ $RUNLEVEL = 0 -o $RUNLEVEL = 6 ]
then
	#
	# run the STOP scripts in boot.d
	#
	for i in /etc/init.d/boot.d/K* ; do
		test -x "$i" || continue
		$i stop < /dev/null || failed=$failed" "$(basename $i)
	done
	#
	# shut down the system
	#
	if [ $RUNLEVEL = 0 ] ; then
	mode=halt ; else mode=reboot ; fi
	/etc/init.d/down $mode | /sbin/btee a /var/log/init.old
	exit 0
else
	#
	# run the START scripts of the current (new) runlevel
	#
	for i in $curdir/S*; do
		test -x "$i" || continue
		$i start < /dev/null || failed=$failed" "$(basename $i)
	done
fi

# status message

if test -n "${failed}" ; then
    c_write "Failed services in runlevel "
    echo -ne ${stat_message_color}${RUNLEVEL}${message_end_color}
    c_write ": "
    echo -e ${fail_message_color}${failed}${message_end_color}
else
    c_write "runlevel "
    echo -ne ${stat_message_color}${RUNLEVEL}${message_end_color}
    c_writeln " has been reached. No Problems."
fi

# write EOT mark for btee
echo -ne '\004'

exit 0
