#!/bin/sh

set -ex

if test -z "$INNER_INVOCATION"; then
	export INNER_INVOCATION=1
	mmdebstrap unstable /dev/null --variant=apt --include=dpkg-dev --customize-hook="upload $0 /doit.sh" --chrooted-customize-hook="sh /doit.sh"
else
	mkdir -p /pkg1/DEBIAN /pkg1/usr/lib/foo /pkg2/DEBIAN /pkg2/lib/foo
	cat >/pkg1/DEBIAN/control <<EOF
Package: pkg1
Architecture: all
Version: 1
EOF
	if test -z "$DO_NOT_MITIGATE"; then
		cat >/pkg1/DEBIAN/postinst <<EOF
#!/bin/sh
mkdir -p /usr/lib/foo
EOF
		chmod 0755 /pkg1/DEBIAN/postinst
		echo "interest-noawait /lib/foo" > /pkg1/DEBIAN/triggers
	fi
	cat >/pkg2/DEBIAN/control <<EOF
Package: pkg2
Architecture: all
Version: 1
EOF
	dpkg-deb -b /pkg1 /pkg1.deb
	dpkg-deb -b /pkg2 /pkg2.deb
	dpkg -i /pkg1.deb /pkg2.deb
	test -d /usr/lib/foo
	dpkg -r pkg2
	if ! test -d /usr/lib/foo; then
		echo "/usr/lib/foo vanished"
		exit 1
	fi
fi
