#!/bin/sh

set -e

kexec_set_config()
{
	# Skip unless running on Debian or a derivative.
	if [ ! -f '/etc/debian_version' ]; then
		return
	fi

	local conffile='/etc/default/kexec'
	local newconf="$(mktemp -- "$conffile.sp-dep.XXXXXX")"

	echo "Trying to set the kexec configuration variables in $conffile"

	perl -pe 's/^\s*LOAD_KEXEC\s*=.*/LOAD_KEXEC=true/; s/^\s*USE_GRUB_CONFIG\s*=.*/USE_GRUB_CONFIG=false/' < "$conffile" > "$newconf" || (rm -f -- "$newconf"; false)

	mv -- "$newconf" "$conffile" || (rm -f -- "$newconf"; false)

	debconf-set-selections <<'EODEBCONF'
kexec-tools	kexec-tools/load_kexec	boolean	true
kexec-tools	kexec-tools/use_grub_config	boolean	false
EODEBCONF

	echo 'Rerunning the kexec-tools configure step'
	env \
		DEBIAN_FRONTEND=noninteractive \
		DPKG_HOOK_ACTION=configure \
		DPKG_MAINTSCRIPT_PACKAGE=kexec-tools \
		DPKG_MAINTSCRIPT_PACKAGE_REFCOUNT=1 \
		DPKG_MAINTSCRIPT_ARCH="$(uname -m)" \
		DPKG_MAINTSCRIPT_NAME=postinst \
		/var/lib/dpkg/info/kexec-tools.postinst configure

	echo 'Making sure it caught...'
	egrep -e '^(LOAD_KEXEC|USE_GRUB_CONFIG)=' -- "$conffile"
	egrep -qe '^LOAD_KEXEC=true' -- "$conffile"
	egrep -qe '^USE_GRUB_CONFIG=false' -- "$conffile"

	echo 'Looks fine!'
}

if [ "$#" -eq 0 ]; then
	cat <<'EOUSAGE' 1>&2
Usage: install-packages name...
Examples:
	install-packages base
	install-packages config common block
EOUSAGE
	exit 1
fi

names=''
for name; do
	depsfile="storpool-$name-deps.txt"
	if [ ! -f "$depsfile" ]; then
		echo "No dependencies file '$depsfile' for name '$name'" 1>&2
		exit 1
	fi
	names="$names $name $(xargs -r < "$depsfile")"
done
names="$(printf -- '%s\n' "$names" | xargs -n1 | sort -u | xargs)"

packages=''
for name in $names; do
	pkgfile="storpool-$name.txt"
	if [ ! -f "$pkgfile" ]; then
		echo "No package filename file '$pkgfile' for name '$name'" 1>&2
		exit 1
	fi
	packages="$packages ./$(cat -- "$pkgfile")"
done

if [ -z "$packages" ]; then
	echo 'Internal error: no packages to install' 1>&2
	exit 1
fi

if [ -f '/etc/debian_version' ]; then
	had_kexec_tools="$(dpkg-query -W -f '${Version}\n' kexec-tools || true)"
else
	had_kexec_tools=''
fi

add_repo="$(pwd)/../add-storpool-repo"
"$add_repo/storpool_variant.sh" command run package.install sp-python2 sp-python2-modules sp-python3 sp-python3-modules

{{ cfg.variant.commands.pkgfile.install[-1] }}

if [ -f '/etc/debian_version' ]; then
	have_kexec_tools="$(dpkg-query -W -f '${Version}\n' kexec-tools || true)"
else
	have_kexec_tools=''
fi

# OK, this is a kind of a hack, but whatever
if [ -z "$had_kexec_tools" ] && [ -n "$have_kexec_tools" ]; then
	kexec_set_config
fi
