#!/bin/bash
. /lib/lsb/init-functions

# Ignore CTRL-C only in this shell, so we can interrupt subprocesses.
trap ":" INT QUIT TSTP

runlevel=$RUNLEVEL
[ "$1" != "" ] && runlevel=$1
if [ "$runlevel" = "" ] ; then
	echo "Usage: $0 <runlevel>" >&2
	exit 1
fi
previous=$PREVLEVEL
[ "$previous" = "" ] && previous=N

get_script_header()
{
	grep -m 1 "# $2:" $1 | sed -e "s/# $2: *//"
}

contains()
{
	for element in $1 ; do
		if [ "$element" = "$2" ] ; then
			return 0
		fi
	done
	return 1
}

[ "$previous" = "N" ] && /etc/init.d/local_fs start
rm -f /var/run/rc/*

scripts=/etc/init.d/*
for script in $scripts ; do
	[ -f $script ] || continue
	provides=$(get_script_header $script "Provides")
	for provide in $provides ; do
		ln -sf $script /var/run/rc/$provide
	done
done

stopgraph=
startgraph=
scripts=/var/run/rc/*
for script in $scripts ; do
	if [ "$previous" != "N" ] && contains "$(get_script_header $script 'Default-Stop')" "$runlevel" && contains "$(get_script_header $script 'Default-Start')" "$previous" ; then
		stopgraph="$stopgraph $(readlink $script) $(readlink $script)"
		requiredstop="$(get_script_header $script 'Required-Stop')"
		shouldstop="$(get_script_header $script 'Should-Stop')"
		for req in $requiredstop $shouldstop ; do
			[ -e /var/run/rc/$req ] || continue
			stopgraph="$stopgraph $(readlink $script) $(readlink /var/run/rc/$req)"
		done
	elif contains "$(get_script_header $script 'Default-Start')" "$runlevel" && ( [ "$previous" = "N" ] || contains "$(get_script_header $script 'Default-Stop')" "$previous" ) ; then
		startgraph="$startgraph $(readlink $script) $(readlink $script)"
		requiredstart="$(get_script_header $script 'Required-Start')"
		shouldstart="$(get_script_header $script 'Should-Start')"
		for req in $requiredstart $shouldstart ; do
			[ -e /var/run/rc/$req ] || continue
			startgraph="$startgraph $(readlink $script) $(readlink /var/run/rc/$req)"
		done
	fi
done

# save tty size as bootlogd prevents accessing it
eval `stty size 2>/dev/null | (read L C; echo export LINES=${L:-24} COLUMNS=${C:-80})`

if [ "$previous" = "N" ] ; then
	start-stop-daemon --start --quiet --exec /sbin/bootlogd -- -r
else
	echo $stopgraph | tsort | grep -v local_fs | (
		while read script ; do
			contains "$(get_script_header $script 'Default-Stop')" "$runlevel" && contains "$(get_script_header $script 'Default-Start')" "$previous" && $script stop
		done
	)
fi

echo $startgraph | tsort | grep -v local_fs | tac | (
	while read script ; do
		contains "$(get_script_header $script 'Default-Start')" "$runlevel" && ( [ "$previous" = "N" ] || contains "$(get_script_header $script 'Default-Stop')" "$previous" ) && $script start
	done
)

if [ "$runlevel" = "0" -o "$runlevel" = "6" ] ; then
	/etc/init.d/local_fs stop
fi

if [ "$runlevel" = "0" ] ; then
	halt -d -f -i -p -h
elif [ "$runlevel" = "6" ] ; then
	reboot -d -f -i
elif [ "$previous" = "N" ] ; then
	start-stop-daemon --stop --quiet --exec /sbin/bootlogd
fi
