#!/bin/sh
#
# 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

# 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

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

# 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

	"$i" stop
done

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

	subsys="${i#$rcd/S??}"

	SourceIfExists /.initrd/initenv

	interactive=
	[ -z "${STOP-}" ] || [ -n "${STOP##*,all,*}" ] || [ -n "${STOP##*,$subsys,*}" ] ||
			interactive=1

	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 "$(replace '[A-Z]' '[a-z]' "$answer")" in
				c|continue)
					printf 'STOP=,,\n' >> /.initrd/initenv
					break
					;;
				s|shell)
					RDSHELL_MESSAGE='This shell remains here for debug purposes. Press Ctrl-D to continue.' \
					/bin/rdshell
					;;
				n|no)
					continue 2
					;;
				y|yes|'')
					break
					;;
			esac
		done
	fi

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

	"$i" start
done
