#!/bin/bash
#
# rc            This file is responsible for starting/stopping
#               services when the runlevel changes.
#
# Original Author:
#               Miquel van Smoorenburg, <miquels@drinkel.nl.mugnet.org>
#

. /etc/init.d/functions
. shell-locks

# Get first argument. Set new runlevel to this argument.
[ $# -eq 0 ] ||
	export runlevel="$1"

locksys="/var/lock/subsys"
rcd="/etc/rc.d/rc$runlevel.d"

# Is there an rc directory for this new runlevel?
[ -d "$rcd" ] ||
	exit 0

exec </dev/console 2>&1
fd_lock 90 /dev/console

msg "INIT: Entering runlevel: $runlevel"

export INITLOG_FILE='/var/log/boot.log'

run_scripts() {
	local s n="$1"
	shift
	for s in /lib/initrd/all/* /lib/initrd/"$n"/*; do
		ExecIfExecutable "$s" "$@"
	done
}

# First, run the KILL scripts.
for i in "$rcd"/K*; do
	[ -x "$i" ] ||
		continue

	subsys=${i#$rcd/K*:}

	# Check if the subsystem is already up.
	[ -f "$locksys/$subsys" ] ||
		continue

	SourceIfExists /.initrd/initenv

	[ "${RDLOG-}" != 'console' ] ||
		export INITLOG_FILE=/dev/console

	run_scripts "pre/$subsys" stop "$subsys"

	"$i" stop
	rc="$?"

	run_scripts "post/$subsys" stop "$subsys" "$rc"
done 90<&-

# Now run the START scripts.
for i in "$rcd"/S*; do
	[ -x "$i" ] ||
		continue

	subsys="${i#$rcd/S*:}"

	SourceIfExists /.initrd/initenv

	[ "${RDLOG-}" != 'console' ] ||
		export INITLOG_FILE=/dev/console

	interactive=
	[ -z "${STOP-}" ] ||
		for n in all "$subsys"; do
			[ -n "${STOP##*,$n,*}" ] || interactive=1
		done

	if [ -n "$interactive" ]; then
		while :; do
			printf 'Start service %s (Y)es/(N)o/(C)ontinue/(S)hell? [Y] ' "$subsys"
			read -r answer < /dev/console
			case "${answer,,}" in
				c|continue)
					printf 'STOP=,,\n' >> /.initrd/initenv
					break
					;;
				s|shell)
					rdshell 'This shell remains here for debug purposes. Press Ctrl-D to continue.'
					;;
				n|no)
					continue 2
					;;
				y|yes|'')
					break
					;;
			esac
		done
	fi

	# Check if the subsystem is already up.
	[ ! -f "$locksys/$subsys" ] ||
		continue

	run_scripts "pre/$subsys" start "$subsys"

	"$i" start
	rc="$?"

	run_scripts "post/$subsys" start "$subsys" "$rc"
done 90<&-

fd_unlock 90
