#!/bin/sh
set -e

. /usr/share/debconf/confmodule

file="$1"

db_get apt-setup/services-select
if ! echo "$RET" | grep -q volatile; then
	exit
fi

db_get apt-setup/volatile_host
host="$RET"
[ "$host" ] || exit

if db_get mirror/codename && [ "$RET" ]; then
	codename="$RET"
	db_get mirror/suite
	suite="$RET"

	if [ "$codename" != "lenny" ]; then
		db_get mirror/protocol
		protocol="$RET"
		db_get mirror/$protocol/hostname
		host="$RET"
		db_get mirror/$protocol/directory
		directory="/${RET#/}"
	fi
else
	db_get cdrom/codename
	codename="$RET"
	db_get cdrom/suite
	suite="$RET"
fi

# To determine if non-free and contrib should be included, grep
# the file to see if they are listed in it.
dists="main"
for dist in contrib non-free; do
	if grep -q '^[^#]* '$dist $ROOT/etc/apt/sources.list.new; then
		dists="$dists $dist"
	fi
done

# Don't test mirror if no network selected in netcfg
if [ "$codename" = "lenny" ]; then
	echo "deb http://$host/debian-volatile $codename/volatile $dists" >> $file
else
	echo "deb $protocol://${host}${directory} ${codename}-updates $dists" >> $file
fi
if db_get netcfg/dhcp_options && \
   [ "$RET" = "Do not configure the network at this time" ]; then
	CODE=9
else
	CODE=0
	export ASV_TIMEOUT="-o Acquire::http::Timeout=30"
	if ! apt-setup-verify --from $PROGRESS_FROM --to $PROGRESS_TO $file; then
		db_subst apt-setup/service-failed HOST "$host"
		db_input critical apt-setup/service-failed || true
		if ! db_go; then
			exit 10 # back up
		fi
		CODE=9
	fi
fi

if [ "$codename" = "lenny" ]; then
	echo "deb-src http://$host/debian-volatile $codename/volatile $dists" >> $file
else
	echo "deb-src $protocol://${host}${directory} ${codename}-updates $dists" >> $file
fi

exit $CODE
