#!/bin/sh

set -e
set -u
set -x

if test -z "${MMDEBSTRAP_HOOK:-}"; then
	exec mmdebstrap \
		sid \
		/dev/null \
		--variant=apt \
		--include=dpkg-dev \
		--hook-dir=/usr/share/mmdebstrap/hooks/merged-usr \
		--customize-hook="upload '$0' /self" \
		--chrooted-customize-hook="sh /self"
fi

: "${TESTCASE:=dpkgremoveb}"

for p in a1 a2 b1 b2; do
	mkdir -p "/testcase/$p/DEBIAN"
done
cat > /testcase/a1/DEBIAN/control <<EOF
Package: a
Version: 1
Architecture: all
Description: a version 1
Maintainer: none <none@invalid.example>
EOF
cat > /testcase/b1/DEBIAN/control <<EOF
Package: b
Version: 1
Architecture: all
Description: b version 1
Maintainer: none <none@invalid.example>
EOF
mkdir -p /testcase/b1/lib
echo b1 > /testcase/b1/lib/flagfile
cat > /testcase/a2/DEBIAN/control <<EOF
Package: a
Version: 2
Architecture: all
Conflicts: b (<< 2)
Description: a version 2
Maintainer: none <none@invalid.example>
EOF
cat > /testcase/a2/DEBIAN/preinst <<EOF
#!/bin/sh

if test "\$(cat /lib/flagfile)" = b1; then
	echo "b (= 1) is unpacked despite conflicts"
fi
EOF
chmod +x /testcase/a2/DEBIAN/preinst
mkdir -p /testcase/a2/usr/lib
echo a2 > /testcase/a2/usr/lib/flagfile
cat > /testcase/b2/DEBIAN/control <<EOF
Package: b
Version: 2
Architecture: all
Description: b version 2
Maintainer: none <none@invalid.example>
EOF
if test "${TESTCASE#apt}" != "$TESTCASE"; then
	echo "Breaks: a (<< 2)" >>/testcase/b2/DEBIAN/control
fi

for p in a1 a2 b1 b2; do
	dpkg-deb --build "/testcase/$p" "/testcase/$p.deb"
done

apt-get -y install /testcase/a1.deb /testcase/b1.deb

case "$TESTCASE" in
	dpkgremoveb)
		echo 'b:all deinstall' | /usr/bin/dpkg --set-selections
		dpkg --auto-deconfigure --unpack /testcase/a2.deb
	;;
	dpkgbadorder)
		# This is how apt invokes dpkg during apt install a2 b2
		echo 'b:all deinstall' | /usr/bin/dpkg --set-selections
		dpkg --auto-deconfigure --unpack /testcase/a2.deb /testcase/b2.deb
	;;
	apt)
		apt-get install /testcase/a2.deb /testcase/b2.deb
	;;
	aptdebug)
		# Shows the commands for dpkgbadorder, but doesn't actually do it
		apt-get -o Debug::pkgDPkgPM=true install /testcase/a2.deb /testcase/b2.deb
	;;
	dpkgrightorder)
		dpkg --auto-deconfigure -i /testcase/b2.deb /testcase/a2.deb
	;;
	dpkgrefuse)
		if dpkg --auto-deconfigure --unpack /testcase/a2.deb /testcase/b2.deb; then
			exit 1
		else
			exit 0
		fi
	;;
esac

flag=$(cat /usr/lib/flagfile)
if test "$flag" != a2; then
	echo "/flagfile has unexpected content >$flag<"
	exit 1
fi
