#! /bin/sh

set -e

PATH=/sbin:/bin:/usr/sbin:/usr/bin
NAME=ubiquity

test -x /usr/bin/ubiquity-dm || exit 0

ubiquity=
automatic=
debug=
noninteractive=
for x in $(cat /proc/cmdline); do
	case $x in
		debug-ubiquity)
			debug="-d"
			ubiquity=1
			;;
		automatic-ubiquity)
			automatic="--automatic"
			ubiquity=1
			;;
		only-ubiquity)
			ubiquity=1
			;;
		noninteractive)
			ubiquity=1
			noninteractive=1
			;;
	esac
done
if [ -z "$ubiquity" ] && [ "$1" != force-start ]; then
	exit 0
fi
    
if [ -r /etc/environment ]; then
	if LANG=$(pam_getenv -l LANG); then
		export LANG
	fi
	if LANGUAGE=$(pam_getenv -l LANGUAGE); then
		export LANGUAGE
	fi
fi

. /lib/lsb/init-functions

case "$1" in
	start|force-start)
		log_begin_msg "Starting Ubiquity..."
		# if usplash is running, make sure to stop it now, yes "start" kills it.
		if pidof usplash > /dev/null; then
			usplash=:
			orig_console="$(fgconsole)"
			DO_NOT_SWITCH_VT=yes /etc/init.d/usplash start
			# We've just shut down usplash, so don't log
			# success as it will look weird on the console.
			log_end_msg=:
		else
			usplash=false
			log_end_msg=log_end_msg
		fi
		# turn off console blanking for install process
		setterm -blank 0
		if [ -n "$noninteractive" ]; then
			cmd="ubiquity noninteractive"
		else
			# Run in the foreground.
			cmd="ubiquity-dm vt7 :0 /usr/bin/ubiquity $debug $automatic --only"
		fi
		if ${cmd}; then
			$log_end_msg 0
		else
			log_end_msg $?
		fi

		if $usplash && [ "$orig_console" != serial ]; then
			# Wait a short while for the active console to
			# change, to try to avoid visible console noise from
			# later init scripts.
			i=0
			while [ "$(fgconsole)" = "$orig_console" ]; do
				i="$(($i + 1))"
				if [ "$i" -gt 5 ]; then
					break
				fi
				sleep 1
			done
		fi
	;;
	stop|restart|force-reload)
	;;
	*)
		N=/etc/init.d/$NAME
		echo "Usage: $N {start|force-start|stop|restart|force-reload}" >&2
		exit 1
	;;
esac

exit 0
