#! /bin/sh -e

. /usr/share/debconf/confmodule

. /lib/kickseed/kickseed.sh
. /lib/kickseed/cmdline.sh
. /lib/preseed/preseed.sh

ks_log () {
	logger -t kickseed "$@"
}

ks_preseed () {
	echo "$@" >> "$SPOOL/parse/preseed.cfg"
}

# No support for chrooting here, as /target isn't available yet and %pre
# scripts don't need it.
ks_run_script () {
	TYPE="$1"
	INTERPRETER="$2"
	SCRIPT="$4"

	logger -t kickseed "Running $TYPE script $SCRIPT using interpreter $INTERPRETER:"
	log-output -t kickseed --pass-stdout "$INTERPRETER" "$SCRIPT"
}

ks_write_script () {
	if [ "${1%/*}" != "$1" ]; then
		mkdir -p "${1%/*}"
	fi
	cat > "$1"
	chmod +x "$1"
}

preseed_fetch () {
	ln -sf "$1" "$2"
}

preseed_relative () {
	if [ -z "${1##/*}" ]; then
		return 1
	else
		return 0
	fi
}

FETCH_ERROR=
fetch_url () {
	local url="$1"
	local file="$2"
	iters=0
	while [ $iters -lt 3 ]; do
		# TODO proxy support? Would it be useful?
		# TODO add progress bar
		if FETCH_ERROR="$(wget -q "$url" -O "$file" 2>&1)"; then
			return 0
		fi
		echo "$FETCH_ERROR" | logger -t kickseed
		iters=$(($iters + 1))
	done
	return 1
}

KS="$(kickseed_cmdline /proc/cmdline ks)"
KSCFG="$(kickseed_file "$KS")"

case $KS in
	ftp://*/*|http://*/*)
		logger -t kickseed "Downloading kickstart file from $KS"
		if ! fetch_url "$KS" "$KSCFG"; then
			logger -t kickseed "... failed"
			db_subst initrd-kickseed/wget-failed URL "$KS"
			db_subst initrd-kickseed/wget-failed \
				ERROR "$FETCH_ERROR"
			db_input high initrd-kickseed/wget-failed || true
			db_go
			exit 1
		fi
		;;
	nfs:*:/*)
		logger -t kickseed "Retrieving kickstart file from $KS"
		file="${KS#nfs:}"
		server="${file%%:*}"
		file="${file#*:}"
		if ! mount -t nfs -o ro,intr,nolock \
				"$server:${file%/*}" "${KSCFG%/*}"; then
			logger -t kickseed "... failed"
			db_subst initrd-kickseed/nfs-mount-failed \
				DIR "${file%/*}"
			db_subst initrd-kickseed/nfs-mount-failed \
				SERVER "$server"
			db_input high initrd-kickseed/nfs-mount-failed || true
			db_go
			exit 1
		fi
		trap "umount '${KSCFG%/*}' || true" \
			EXIT HUP INT QUIT TERM
		;;
esac

case $KSCFG in
	/floppy/*)
		mountmedia floppy || true
		KSCFG="/media/${KSCFG#/floppy/}"
		trap 'umount /media || true' EXIT HUP INT QUIT TERM
		;;
	/media/*)
		device="${KSCFG#/media/}"
		device="${device%%/*}"
		# TODO: relies on having non-devfs compatibility paths
		if log-output -t kickseed \
				mount "/dev/$device" "/media/$device"; then
			trap "umount '/media/$device' || true" \
				EXIT HUP INT QUIT TERM
		fi
		;;
esac

case $KSCFG in
	'')
		# not handled in initrd (yet?)
		: ;;
	*)
		logger -t kickseed "Reading kickstart file from $KSCFG"

		kickseed "$KSCFG"

		if [ -s "$SPOOL/parse/preseed.cfg" ]; then
			preseed_location "$SPOOL/parse/preseed.cfg"
		fi
		;;
esac
