#!/bin/sh

set -e

# cargo-culted from grub
merge_debconf_into_conf() {
	local tmpfile; tmpfile="$1"
	local setting; setting="$2"
	local template; template="$3"

	db_get "$template"
	local value; value="$(echo "$RET" | sed -e 's,[$`"\],\\&,g')"
	if grep -q "^${setting}=" "$tmpfile"; then
		value="$(echo "$value" | sed -e 's,[\@],\\&,g')"
		sed -i -re "s@^(${setting}=).*@\1\"${value}\"@" "$tmpfile"
	else
		echo >> "$tmpfile"
		echo "${setting}=\"${value}\"" >> "$tmpfile"
	fi
}

case "$1" in
	configure)
		. /usr/share/debconf/confmodule

		tmp_default_fk="$(mktemp -t flash-kernel.XXXXXXXXXX)"
		tmp_default_fk_old_md5s="$(mktemp -t flash-kernel.md5sums.XXXXXXXXXX)"
		trap "rm -f ${tmp_default_fk} ${tmp_default_fk_old_md5s}" EXIT
		cp -p /usr/share/flash-kernel/default/flash-kernel \
			${tmp_default_fk}
		echo "6d73d0418e01f86e006d590e4b1ca85e" > ${tmp_default_fk_old_md5s}
		merge_debconf_into_conf "$tmp_default_fk" \
			LINUX_KERNEL_CMDLINE flash-kernel/linux_cmdline

		ucf --three-way --debconf-ok --sum-file ${tmp_default_fk_old_md5s} \
			${tmp_default_fk} \
			/etc/default/flash-kernel
		ucfr flash-kernel /etc/default/flash-kernel
		;;
	triggered|abort-upgrade|abort-remove|abort-deconfigure)
		;;
	*)
		echo "postinst called with unknown argument \`$1'" >&2
		exit 1
		;;
esac

if [ -n "$FLASH_KERNEL_SKIP" ]; then
	# we dont want to run if FLASH_KERNEL_SKIP is set, the ubuntu image build
	# system uses this
	echo "FLASH_KERNEL_SKIP is set, skipping flash-kernel call"
	exit 0
else
	if [ "x$1" = xtriggered ]; then
		# this forces flash-kernel to run rather than setting our trigger to
		# cause a later run (as happens without _NOTRIGGER being set)
		FLASH_KERNEL_NOTRIGGER=y flash-kernel
	else
		flash-kernel
	fi
fi

#DEBHELPER#
