#!/bin/sh -eu

. rdshell-sh-functions

for f in /.initrd/initenv /etc/sysconfig/rdshell; do
	[ ! -f "$f" ] || . "$f"
done

msg=
if [ -z "${RDSHELL_NOMESSAGE-}" ]; then
	if [ -z "${RDSHELL_MESSAGE-}" ]; then
		if [ -e "$rdshell_fifo" ]; then
			read -r msg < "$rdshell_fifo" ||:
		fi
	else
		msg="$RDSHELL_MESSAGE"
	fi
fi

while ! console_lock; do
	sleep 0.5
done

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

[ -z "${msg-}" ] || printf '%s: %s\n' "${0##*/}" "$msg"

RDSHELL_MODE="${RDSHELL_MODE:-shell}"

# Disallow console access
[ "${PANIC-}" != 0 ] || [ "$RDSHELL_MODE" != shell ] || RDSHELL_MODE=disable

shcmd='/bin/sh -l'
case "${RDSHELL_MODE-}" in
	shell)
		;;
	login)
		printf '\n'
		shcmd='sulogin'
		;;
	disable)
		printf 'Shell access is not allowed.\n'
		while sleep 1; do :; done
		;;
esac

for f in /lib/shell/*; do
	[ -x "$f" ] || break
	"$f" ||:
done

setsid -c $shcmd
console_unlock
