#!/bin/sh

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

diverted="zcat zcmp zdiff zegrep zfgrep zgrep"

properly_diverted() {
	test -e "$1/usr/bin/$2.gzip" -o -h "$1/usr/bin/$2.gzip" -o -e "$1/bin/$2.gzip.usr-is-merged" -o -h "$1/bin/$2.gzip.usr-is-merged"
}

if test -n "$MMDEBSTRAP_HOOK"; then
	if dpkg-query --root "$1" -f '${db:Status-Status}\n' -W zutils| grep -q '^installed$'; then
		for cmd in $diverted; do
			properly_diverted "$1" "$cmd" || {
				ls -la "$1/usr/bin"
				PAGER=cat dpkg --root "$1" -l gzip zutils
				die "diversion check failed for $cmd"
			}
		done
	else
		for cmd in $diverted; do
			properly_diverted "$1" "$cmd" && {
				ls -la "$1/usr/bin"
				PAGER=cat dpkg --root "$1" -l gzip zutils
				die "non-diversion check failed for $cmd"
			}
		done
	fi
	exit 0
fi

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

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

while test "${fromcase#*-}" != "$fromcase"; do
	thing="${fromcase%%-*}"
	fromcase="${fromcase#*-}"
	case "$thing" in
		zutils)
			includepkgs="${includepkgs:+"$includepkgs,"}zutils"
		;;
		newzutils)
			preinstallpkgs="${preinstallpkgs:+"$preinstallpkgs "}/zutils.deb"
		;;
		newgzip)
			preinstallpkgs="${preinstallpkgs:+"$preinstallpkgs "}/gzip.deb"
		;;
		"")
		;;
		*)
			die "unrecognized from thing: $thing"
		;;
	esac
done

while test "${tocase#*-}" != "$tocase"; do
	thing="${tocase%%-*}"
	tocase="${tocase#*-}"
	case "$thing" in
		gzip)
			installpkgs="${installpkgs:+"$installpkgs "}/gzip.deb"
		;;
		zutils)
			installpkgs="${installpkgs:+"$installpkgs "}/zutils.deb"
		;;
		rmzutils)
			installpkgs="${installpkgs:+"$installpkgs "}zutils-"
		;;
		"")
		;;
		*)
			die "unrecognized to thing: $thing"
		;;
	esac
done

set -- --variant=apt "$basedist" /dev/null "$mirror"
test -n "$includepkgs" && set -- "$@" --include="$includepkgs"
set -- "$@" --customize-hook="$0"
set -- "$@" --customize-hook="upload gzip_1.12-1.1_amd64.deb /gzip.deb"
set -- "$@" --customize-hook="upload zutils_1.12-3.1_amd64.deb /zutils.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"
set -- "$@" --customize-hook="$0"
test -n "$installpkgs" || die "no packages to install"
set -- "$@" --chrooted-customize-hook="apt-get -y install $installpkgs"
set -- "$@" --customize-hook="$0"

exec auto-apt-proxy mmdebstrap "$@"
