#!/bin/sh
# Finish up the install, clean up anything necessary, and get the user to a
# login prompt.
set -e

. /usr/share/debconf/confmodule

db_capb backup

if [ "$1" = new ]; then
	# en_US is treated as a special case, because it is the default.
	# If d-i used C for the default, we could remove this special case.
	if [ -n "$LANG" ] && [ "$LANG" != en_US ]; then
		if [ -e /etc/environment ]; then
			grep -v "^LANG=" /etc/environment > /etc/environment.new || true
			mv /etc/environment.new /etc/environment
			echo "LANG=$LANG" >> /etc/environment
		else
			echo "LANG=$LANG" > /etc/environment
		fi

		# fix GDM language problem
		if [ -e /etc/default/gdm ]; then
			sed -i "s,^#*LANG=$,LANG=$LANG,g" /etc/default/gdm
		fi
	fi
	
	# If a display manager is installed, ask about starting it.
	SERVICES=""
	for service in xdm gdm kdm; do
		if test -x /etc/init.d/$service; then
			SERVICES="$service $SERVICES"
		fi
	done
	if [ "$SERVICES" ]; then
		db_fset base-config/start-display-manager seen false
		db_input low base-config/start-display-manager || true
		db_go || exit 30 # back up to menu
	fi
	
	# Display the final message.
	db_fset base-config/login seen false
	db_input high base-config/login || true
	db_go || exit 30 # back up to menu TODO should use state machine
	
	# Turn on console screen blanking again
	if which setterm >/dev/null 2>&1; then
		# It seem to be impossible to get the current timeout
		# value before changing it, so the only way to
		# undo the setting is to set the timeout period to some
		# random value. 10 minutes sounds like a good value.
		setterm -blank 10 </dev/tty >/dev/tty
	fi

	# Start the display manager
	db_get base-config/start-display-manager
	if [ "$RET" = true ]; then
		for service in $SERVICES ; do
			# Try to avoid trouble with debconf.
			/etc/init.d/$service restart </dev/tty >/dev/tty 3>/dev/null || true
		done
	fi

	# Finally, put the real inittab into place and tell init.
	if [ -f /etc/inittab.real ]; then
		mv -f /etc/inittab.real /etc/inittab
		telinit q >/dev/null
		# Clear the screen, in preparation for the login prompt
		clear </dev/tty >/dev/tty
	fi
fi
