#!/bin/sh
set -e

. /usr/share/debconf/confmodule

file="$1"

# Abort if no mirror is configured.
db_get mirror/codename
codename="$RET"
db_get mirror/protocol
protocol="$RET"
db_get mirror/$protocol/hostname
hostname="$RET"
db_get mirror/$protocol/directory
directory="/${RET#/}"
if [ -z "$hostname" ] || [ -z "$directory" ]; then
	exit 0
fi

STATE=1
while true; do
	case "$STATE" in
		1)
			db_input low apt-setup/non-free || true
		;;
		2)
			# If they chose not to use non-free, ask about
			# contrib, with a default of no. If they chose to
			# use non-free, they get contrib too..
			db_get apt-setup/non-free
			if [ "$RET" = false ]; then
				db_fget apt-setup/contrib seen
				if [ "$RET" = false ]; then
					db_set apt-setup/contrib false
				fi
				db_input low apt-setup/contrib || true
			else
				db_fget apt-setup/contrib seen
				if [ "$RET" = false ]; then
					db_set apt-setup/contrib true
				fi
			fi
		;;
		*)
			break
		;;
	esac

	if db_go; then
		STATE=$(($STATE + 1))
	else
		STATE=$(($STATE - 1))
	fi
done
if [ $STATE -eq 0 ]; then
	exit 10
fi

dists="main"
db_get apt-setup/non-free
if [ "$RET" = true ]; then
	dists="$dists non-free"
fi
db_get apt-setup/contrib
if [ "$RET" = true ]; then
	dists="$dists contrib"
fi

done=""
while [ ! "$done" ]; do
	db_get mirror/codename
	codename="$RET"
	db_get mirror/protocol
	protocol="$RET"
	db_get mirror/$protocol/hostname
	hostname="$RET"
	db_get mirror/$protocol/directory
	directory="/${RET#/}"

	if [ "$protocol" = http ]; then
		db_get mirror/$protocol/proxy
		proxy="$RET"
		if [ -n "$proxy" ]; then
			if ! grep -iq "Acquire::$protocol::Proxy" $ROOT/etc/apt/apt.conf.new; then
				echo "Acquire::$protocol::Proxy \"$proxy\";" >> $ROOT/etc/apt/apt.conf.new
			fi
		fi
	fi

	echo "deb $protocol://$hostname$directory $codename $dists" > $file
	
	if apt-setup-verify $file; then
		done=1
	else
		db_set apt-setup/mirror/error Retry
		db_input critical apt-setup/mirror/error || true
		db_go || exit 10
		db_get apt-setup/mirror/error
		if [ "$RET" = "Change mirror" ]; then
			choose-mirror || true
		elif [ "$RET" = Ignore ]; then
			exit 1
		fi
	fi
done

echo "deb-src $protocol://$hostname$directory $codename $dists" >> $file
