#! /bin/sh
# This is where the installer actually interacts with the user
set -e

SCREEN_BIN=/usr/bin/screen
SSHD_BIN=/usr/sbin/sshd

# GNU/screen support status by target
#   - netboot:					no GNU/screen support
#   - netboot/network-console:	no GNU/screen support
#   - netboot-screen:			start GNU/screen in netboot (serial console)
#   - netboot/network-screen:	follow the rules below:
#				NETBOOT_SCREEN
#					= 0 :		start GNU/screen in network-console (SSH session, by default)
#					= 1 :		start GNU/screen in netboot (serial console, only for testing)
NETBOOT_SCREEN=0

if [ -x "$SCREEN_BIN" ]; then
	# there's GNU/screen binary
	if [ -z "$STY" ]; then
		# now it's NOT inside GNU/screen
		if [ ! -x "$SSHD_BIN" ] ||	# there's no SSHD; target: netboot-screen
		  # there's SSHD; target: netboot/network-screen
		  [ -x "$SSHD_BIN" -a $NETBOOT_SCREEN -eq 1 -a -z "$SSH_CLIENT" ] ||	# case of serial console session
		  [ -x "$SSHD_BIN" -a $NETBOOT_SCREEN -ne 1 -a -n "$SSH_CLIENT" ]; then	# case of SSH session
			# call this script again with in GNU/screen, in UTF-8 mode, with same TERM setting
			[ -d /usr/lib/locale/C.UTF-8 ] &&
				UTF="-U"
			SCREEN_OPT="-T $TERM $UTF $0 $@"
			[ -d /var/run/screen/S-root -a -e /var/run/screen/S-root/* ] &&
				SCREEN_OPT="-r"		# If GNU/screen is already started, just resume it
			exec /usr/bin/screen $SCREEN_OPT
			exit 0
		fi
	else # This is called within GNU/screen
		# set title of current screen window
		printf "\033k%s\033\\" installer
		# wrong TERMCAP prevents d-i to get started
		unset TERMCAP
	fi
fi

export MENU=${MENU:-${1:-/usr/bin/main-menu}}
for script in /lib/debian-installer.d/S[0-9][0-9]*; do
	. $script
done
