#!/bin/sh -fu

# Save kernel environment and init arguments
[ -f /.initrd/kernenv ] ||
	/bin/showenv | /bin/grep -vE -e '^(_|PWD|SHLVL)=' > /.initrd/kernenv ||:

[ -f /.initrd/initargs ] ||
	echo "$*" > /.initrd/initargs

# Create storage for init environment
:> /.initrd/initenv

# Backward compatibility
x=/sbin/init-bin
[ ! -x "$x" ] || exec "$x"

trap : CHLD INT TSTP QUIT HUP

. rdshell-sh-functions

x=/etc/rc.d/rc.sysinit
[ ! -x "$x" ] || setsid "$x" ||:

msg() {
	/sbin/monotonic-timestamp
	echo "INIT: $*"
}

lock=/tmp/rc.lock
lock() {
	while ! mkdir -- "$lock" >/dev/null 2>&1; do
		sleep 0.1
	done
	while ! console_lock; do
		sleep 0.5
	done
}

unlock() {
	console_unlock
	rmdir -- "$lock"
}

level=3
rc=
rc_pid=

while :; do
	[ -z "$rc" ] || {
		read -r level < /.initrd/telinit
	} 2>/dev/null ||:

	case "$level" in
		[0-6])
			[ "$rc" != "$level" ] ||
				continue

			rc="$level"

			lock
			{
				lock
				[ -z "$rc_pid" ] ||
					rm -f -- "$rc_pid"

				msg "Entering runlevel: $level"

				setsid /etc/rc.d/rc "$level" ||:
				unlock
			} &

			rc_pid="/.initrd/killall/$!"
			:>"$rc_pid"

			unlock
			;;
		9)
			lock

			. /.initrd/initenv

			! mountpoint -q /proc ||
				umount -fl /proc

			msg "Running init ($INIT)"

			# Run system init with arguments. Goodbye!
			exec runas /sbin/init /bin/run-init -e /.initrd/kernenv "$rootmnt" "$INIT" "$@"
			;;
	esac
done
