#!/bin/sh
set -e
. /usr/share/debconf/confmodule

# Avoid perl warnings in any of the chroot calls below.
LANG=C
export LANG

DIVERTS='/usr/bin/scrollkeeper-update /usr/bin/scrollkeeper-rebuilddb /usr/bin/fc-cache'

log() {
	logger -t pkgsel "$@"
}

cleanup () {
	# If X was not installed, remove the hardware detection programs.
	if ! chroot /target dpkg --get-selections | grep 'xserver-\(xfree86\|xorg\)' | grep -q install
	then
		in-target dpkg --purge xresprobe laptop-detect discover1 libdiscover1 discover1-data
	fi

	for divert in $DIVERTS; do
		rm -f "/target$divert"
		log-output -t pkgsel chroot /target dpkg-divert \
			--package pkgsel --rename --quiet --remove "$divert"
	done
}

langsupport_on_cd () {
	for l; do
		if ! [ "$(chroot /target apt-cache -n search "^language-support-$l\$")" ]; then
			return 1
		fi
	done
	return 0
}

have_networking () {
	# This is a nasty way to check whether we ought to have a network
	# connection; if we don't, it isn't worthwhile to ask whether to
	# download language support. We should really change netcfg to write
	# out a flag somewhere.
	! db_get netcfg/dhcp_options || [ "${RET#Do not configure}" = "$RET" ]
}

db_progress START 0 1000 debian-installer/pkgsel/title
db_progress INFO pkgsel/progress/init

# d-i debconf variables used by packages
debconf-copydb -p \
	"^(debian-installer/language|debian-installer/country|debian-installer/keymap|passwd/username)$" \
	configdb target_configdb

# scrollkeeper takes forever, so divert it for the duration
for divert in $DIVERTS; do
	log-output -t pkgsel chroot /target dpkg-divert --package pkgsel \
		--rename --quiet --add "$divert"
	ln -sf /bin/true "/target$divert"
done

# get debconf-apt-progress config, which will make it run properly later
config=$(chroot /target debconf-apt-progress --config| sed "s/$/;/")

# Work out what we need to install.

if db_get base-config/package-selection; then
	# backward compatibility
	pattern="$RET"
else
	db_get pkgsel/install-pattern
	pattern="$RET"
fi

if db_get base-config/language-packs && [ "$RET" ]; then
	# backward compatibility
	langpacks="$(echo "$RET" | sed 's/,//g')"
elif db_get pkgsel/language-packs && [ "$RET" ]; then
	langpacks="$(echo "$RET" | sed 's/,//g')"
elif db_get localechooser/supported-locales && [ "$RET" ]; then
	langpacks="$(for loc in $(echo "$RET" | sed 's/,//g'); do
		echo "${loc%%_*}"
	done | sort -u)"
else
	db_get debian-installer/locale
	langpacks="${RET%%_*}"
fi

if db_get base-config/install-language-support; then
	# backward compatibility
	langsupport="$RET"
else
	if [ -f /cdrom/.disk/base_installable ] && \
	   ! langsupport_on_cd $langpacks; then
		log "language-support packages not available on CD"
		if have_networking; then
			db_capb
			db_input high pkgsel/install-language-support || true
			db_go || true
			db_capb backup
		else
			log "... but no network is available"
		fi
	fi
	db_get pkgsel/install-language-support
	langsupport="$RET"
fi

if [ "$langpacks" ]; then
	db_get pkgsel/language-pack-patterns
	lppatterns="$RET"
	numpacks="$(set -- $langpacks; echo $#)"
	numpatterns="$(set -- $lppatterns; echo $#)"
	if [ "$langsupport" = true ]; then
		numpatterns="$(($numpatterns + 1))"
	fi
	numlangs="$(($numpacks * $numpatterns))"
fi

db_progress STEP 10

# Install basic language packs, required to get localisation working at all.
# We install these almost unconditionally; if you want to get rid of even
# these, you can preseed pkgsel/language-packs to the empty string.
curlang=0
for lp in $langpacks; do
	min="$((10 + 10 * $curlang / $numpacks))"
	curlang="$(($curlang + 1))"
	max="$((10 + 10 * $curlang / $numpacks))"
	ret=0
	in-target sh -c "$config debconf-apt-progress --from $min --to $max --logstderr -- aptitude -q --without-recommends -y install 'language-pack-$lp'" || ret=$?
	if [ "$ret" != 0 ]; then
		# In case packages failed to install, try to clean up.
		in-target dpkg --configure -a || true
	fi
done

# See if any known X servers are available.
if chroot /target apt-cache show xserver-xfree86 xserver-xorg >/dev/null 2>&1; then
	# 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.
	in-target sh -c "$config debconf-apt-progress --from 20 --to 30 --logstderr -- apt-get -q -y -f install xresprobe" || true
	in-target sh -c "$config debconf-apt-progress --from 30 --to 40 --logstderr -- apt-get -q -y -f install laptop-detect" || true
	in-target sh -c "$config debconf-apt-progress --from 40 --to 50 --logstderr -- apt-get -q -y -f install discover1" || true
fi

ret=0
in-target sh -c "$config debconf-apt-progress --from 50 --to 860 --logstderr -- aptitude -q --without-recommends -y install '$pattern'" || ret=$?
if [ "$ret" != 0 ]; then
	# In case packages failed to install, try to clean up.
	in-target dpkg --configure -a || true
	
	# TODO useful error message here (for ret != 30)
	db_progress INFO pkgsel/progress/cleanup
	if ! cleanup; then
		log "cleanup failed"
	fi
	db_progress STOP
	exit $ret
fi

# Move final sources.list into place, if necessary, so that language packs
# that aren't on the CD can be installed.
if [ -f /target/etc/apt/sources.list.apt-setup ]; then
	mv -f /target/etc/apt/sources.list.apt-setup \
		/target/etc/apt/sources.list
	in-target apt-get update || true
fi

curlang=0
for lp in $langpacks; do
	for pattern in $lppatterns; do
		min="$((850 + 100 * $curlang / $numlangs))"
		curlang="$(($curlang + 1))"
		max="$((850 + 100 * $curlang / $numlangs))"
		pack="$(echo "$pattern" | sed "s/\\\$LL/$lp/g")"
		ret=0
		in-target sh -c "$config debconf-apt-progress --from $min --to $max --logstderr -- aptitude -q --without-recommends -y install '$pack'" || ret=$?
		if [ "$ret" != 0 ]; then
			# In case packages failed to install, try to clean up.
			in-target dpkg --configure -a || true
		fi
	done
	if [ "$langsupport" = true ]; then
		min="$((850 + 100 * $curlang / $numlangs))"
		curlang="$(($curlang + 1))"
		max="$((850 + 100 * $curlang / $numlangs))"
		ret=0
		in-target sh -c "$config debconf-apt-progress --from $min --to $max --logstderr -- aptitude -q --without-recommends -y install 'language-support-$lp'" || ret=$?
		if [ "$ret" != 0 ]; then
			# In case packages failed to install, try to clean up.
			in-target dpkg --configure -a || true
		fi
	fi
done
if [ -z "$langpacks" ]; then
	db_progress SET 950
fi

db_progress INFO pkgsel/progress/cleanup
if ! cleanup; then
	log "cleanup failed"
fi
db_progress STEP 20

# Mark any pending update notifications as seen.
if [ -d /target/var/lib/update-notifier/user.d ]; then
	mkdir -p /target/etc/update-notifier
	chroot /target find /var/lib/update-notifier/user.d/ -type f \
		-printf '%P %C@ 0\n' \
		> /target/etc/update-notifier/hooks_seen
fi

if [ -x /target/usr/bin/scrollkeeper-update ]; then
	log-output -t pkgsel chroot /target scrollkeeper-update -q || true
fi
if [ -x /target/usr/bin/fc-cache ]; then
	chroot /target fc-cache -f -v >/target/var/log/fontconfig.log 2>&1 \
		|| true
fi

db_progress STEP 30
db_progress STOP
