#!/bin/bash -e
# Run apt to install any selected packages.

case "$1" in
''|new)
	clear

	# Make dpkg not background itself to get a shell.
	export DPKG_NO_TSTP="yes"
	
	# Set DEBIAN_FRONTEND, since some evil postinst scripts still
	# check it directly.
	if [ -z "$DEBIAN_FRONTEND" ] ; then
		DEBIAN_FRONTEND=$($0 get_frontend 4>&1 || true)
		if [ "$DEBIAN_FRONTEND" ] ; then
			export DEBIAN_FRONTEND
		else
			unset DEBIAN_FRONTEND || true
		fi
	fi
	
	if apt-get -y -f dselect-upgrade; then
		if [ "$KEEP_BASE_DEBS" != yes ]; then
			apt-get -f clean || true
		fi
	else
		$0 failure
		# Jump to the menu.
		exit 1
	fi

	# If X was not installed, remove the three hardware detection
	# programs. Of course, this fails if the user manually picked
	# to install these, or wants them installed for some other reason.
	# But I cannot help that.
	if ! dpkg --get-selections | grep xserver-xfree86 | grep -q install; then
		if [ -f $TMPDIR/tmp-Xhack ] ; then
			extra=`cat $TMPDIR/tmp-Xhack`
			dpkg --purge $extra >/dev/null 2>&1 || true
			rm $TMPDIR/tmp-Xhack
		fi
	fi
	;;
failure)
	# This branch is reached if there was some problem installing.
	# It uses debconf (which the other branch cannot use) to explain
	# the failure to the user.
	. /usr/share/debconf/confmodule
	db_settitle base-config/title
	db_fset base-config/install-problem seen false
	db_input critical base-config/install-problem || true
	db_go || true
	;;
get_frontend)
	. /usr/share/debconf/confmodule
	db_get debconf/frontend
	# Convert to lower case to avoid warning from newer debconf
	echo $RET | tr A-Z a-z >&4
	;;
esac
