#!/bin/sh
# Run various programs to select packages to install.
set -e

# As two of those programs (aptitude, dselect) can be made to install
# packages, debconf cannot be run in the main part of this script. Instead
# it is run inside here.
if [ "$1" = select ]; then
	. /usr/share/debconf/confmodule

	db_capb backup
	db_settitle base-config/title

	# Building up the choices list is a little bit nasty.
	choices=""
	# Note that the list is in reverse order to what is displayed,
	# since new items are prepended as the string is built up.
	# The last item found will be the default.
	for program in "dselect" "aptitude" "tasksel"; do
		if which $program >/dev/null 2>&1; then
			case "$program" in
			dselect)
				entry=`gettext "dselect - old package selector (experts only)"`
			;;
			aptitude)
				entry=`gettext "aptitude - pick tasks or drill down to individual packages"`
			;;
			tasksel)
				entry=`gettext "tasksel - quickly choose from predefined collections of software"`
			;;
			esac
			choices="$entry, $choices"
			db_set base-config/pkgsel "$entry"
		fi
	done
	choices="$choices "`gettext "nothing - you may manually run apt-get or any of the above later"`
	db_subst base-config/pkgsel choices $choices
	db_fset base-config/pkgsel seen false
	db_input high base-config/pkgsel || true
	db_go || exit 30 # to main menu
	db_get base-config/pkgsel
	echo $RET >&5 # to the caller on special fd
else
	run () {
		# Make dpkg not background itself to get a shell.
		export DPKG_NO_TSTP="yes"
			
		clear
		$1 $2 $3 $4 $5 $6 $7 $8 || true
		clear
	}

	
	# Make popularity-contest be selected for installation by default. It
	# lets the user choose whether or not to enable it. We need more
	# people using this so we can hope to get better data about who is
	# using what packages in debian.
	echo popularity-contest install | dpkg --set-selections
	
	# X needs some packages installed before its debconf config is run
	# to make it do hardware autodetection. The only way to make sure these
	# are installed properly is to install them now, before packages are
	# selected. This way, even if the user picks xserver-xfree86 in
	# aptitude and installs using aptitude, they will be available.
	for pkg in mdetect read-edid ; do
		if ! dpkg --get-selections | grep "$pkg" | grep -q install; then
			extra="$pkg $extra"
		fi
	done
	if [ "$extra" ] ; then
		apt-get -y -f install $extra >/dev/null 2>&1 || true
		# They are removed later on if it looks like X was not selected.
		echo $extra > $TMPDIR/tmp-Xhack
	fi
	
	# Get the program to run. Gross.
	TMP=$(tempfile)
	$0 select 5>$TMP
	SEL="`cat $TMP`"
	rm -f $TMP
	
	# I'm banking on the program names not being translated to
	# something else, since I have to match against possibly localized
	# return values. Of course "nothing" may be translated, so I match
	# it at the end.
	case "$SEL" in
	*dselect*)
		run dselect select
	;;
	*aptitude*)
		run aptitude
	;;
	*tasksel*)
		run tasksel -riqs
	;;
	*)
		exit 0
	esac
fi
