#! /bin/sh

PREREQ=""
DESCRIPTION="Loading preseed file..."

. /scripts/casper-functions

prereqs ()
{
	echo "$PREREQ"
}

case $1 in
# get pre-requisites
prereqs)
	prereqs
	exit 0
	;;
esac

log_begin_msg "$DESCRIPTION"

if [ -e /preseed.cfg ]; then
	chroot /root debconf-set-selections < /preseed.cfg
fi

location=
for x in $(cat /proc/cmdline); do
	case $x in
		preseed/file=*)
			location="${x#preseed/file=}"
			;;
		file=*)
			location="${x#file=}"
			;;
		url=*)
			location="${x#url=}"
			mount -n -o bind /sys /root/sys
			mount -n -o bind /proc /root/proc
			mount -n -o bind /dev /root/dev
			mkdir -p /root/var/run/network
			chroot /root dhclient eth0
			chroot /root wget -P /tmp "$location"
			chroot /root ifconfig eth0 down
			umount /root/sys
			umount /root/proc
			umount /root/dev
			location="/tmp/$(basename "$location")"
			;;
		*/*=*)
			question="${x%%=*}"
			value="${x#*=}"
			casper-preseed /root "$question" "$value"
			;;
		locale=*)
			value="${x#*=}"
			casper-preseed /root debian-installer/locale "$value"
			;;
	esac
done

if [ "$location" ]; then
	chroot /root debconf-set-selections < "/root$location"
fi

reply="$(echo "GET preseed/early_command" | chroot /root debconf-communicate -fnoninteractive casper)"
if [ "${reply#0 }" != "$reply" ]; then
	reply="${reply#0 }"
	sh -c "$reply"
fi

# Clear out debconf database backup files to save memory.
rm -f /root/var/cache/debconf/*.dat-old

log_end_msg

exit 0
