#!/bin/sh

die() {
	echo "error: $*" 1>&2
	exit 1
}

if test -n "$MMDEBSTRAP_HOOK"; then
	if dpkg-query --root "$1" -f '${db:Status-Status}\n' -W molly-guard| grep -q '^installed$'; then
		if dpkg-query --root "$1" -f '${db:Status-Status}\n' -W systemd-sysv sysvinit-core | grep -q '^installed$'; then
			test -e "$1/usr/lib/molly-guard/reboot" || {
				ls -la "$1/usr/lib/molly-guard"
				die "init installed, but reboot missing"
			}
		else
			test -e "$1/usr/lib/molly-guard/reboot" -o -h "$1/usr/lib/molly-guard/reboot" && {
				ls -la "$1/usr/lib/molly-guard"
				die "no init, but reboot present"
			}
		fi
	else
		test -d "$1/usr/lib/molly-guard" && {
			ls -la "$1/usr/lib/molly-guard"
			die "molly-guard removed, but libdir remains"
		}
	fi
	exit 0
fi

fromcase="$1-"
tocase="$2-"

basedist=trixie
nextdist=sid
mirror=http://deb.debian.org/debian
includepkgs=
preinstallpkgs=

while test "${fromcase#*-}" != "$fromcase"; do
	thing="${fromcase%%-*}"
	fromcase="${fromcase#*-}"
	case "$thing" in
		molly)
			includepkgs="${includepkgs:+"$includepkgs,"}molly-guard"
		;;
		sidmolly)
			preinstallpkgs="${preinstallpkgs:+"$preinstallpkgs "}molly-guard"
		;;
		newmolly)
			preinstallpkgs="${preinstallpkgs:+"$preinstallpkgs "}/molly-guard.deb"
		;;
		systemd)
			includepkgs="${includepkgs:+"$includepkgs,"}systemd-sysv"
		;;
		sidsystemd)
			preinstallpkgs="${preinstallpkgs:+"$preinstallpkgs "}systemd-sysv"
		;;
		sysvinit)
			includepkgs="${includepkgs:+"$includepkgs,"}sysvinit-core"
		;;
		"")
		;;
		*)
			die "unrecognized from thing: $thing"
		;;
	esac
done

while test "${tocase#*-}" != "$tocase"; do
	thing="${tocase%%-*}"
	tocase="${tocase#*-}"
	case "$thing" in
		molly)
			installpkgs="${installpkgs:+"$installpkgs "}/molly-guard.deb"
		;;
		rmmolly)
			installpkgs="${installpkgs:+"$installpkgs "}molly-guard-"
		;;
		systemd)
			installpkgs="${installpkgs:+"$installpkgs "}systemd-sysv"
		;;
		rmsystemd)
			installpkgs="${installpkgs:+"$installpkgs "}systemd-sysv-"
		;;
		sysvinit)
			installpkgs="${installpkgs:+"$installpkgs "}sysvinit-core"
		;;
		rmsysvinit)
			installpkgs="${installpkgs:+"$installpkgs "}sysvinit-core-"
		;;
		"")
		;;
		*)
			die "unrecognized to thing: $thing"
		;;
	esac
done

set -- --variant=apt "$basedist" /dev/null "$mirror"
test -n "$includepkgs" && set -- "$@" --include="$includepkgs"
set -- "$@" --customize-hook="upload molly-guard_0.8.1+nmu1_all.deb /molly-guard.deb"
set -- "$@" --customize-hook='sed -i -e "'"s/$basedist/$nextdist/"'" "$1/etc/apt/sources.list"'
set -- "$@" --chrooted-customize-hook="apt-get update"
test -n "$preinstallpkgs" && set -- "$@" --chrooted-customize-hook="apt-get -y install $preinstallpkgs"
test -n "$installpkgs" || die "no packages to install"
set -- "$@" --chrooted-customize-hook="apt-get -y install $installpkgs"
set -- "$@" --customize-hook="$0"
set -- "$@" --chrooted-customize-hook="apt-get -y remove molly-guard"
set -- "$@" --customize-hook="$0"

exec auto-apt-proxy mmdebstrap "$@"
