#!/bin/sh

if test "$#" -ne 2; then
	echo "$(basename "$0") takes two positional arguments: architecture and release" 1>&2
	exit 1
fi
ARCHITECTURE=$1
RELEASE=$2
SSH_KEYPATH=ssh_id
IMAGE=test.ext4

set -eux

. "$(dirname "$0")/test_common.sh"

cleanup() {
	rm -f "$SSH_KEYPATH" "$SSH_KEYPATH.pub" "$IMAGE"
}

trap cleanup EXIT INT TERM QUIT

ssh-keygen -f "$SSH_KEYPATH" -N ''
MIRROR=
if test -n "$RELEASE" && ! curl -s "http://deb.debian.org/debian/dists/$RELEASE/InRelease" | sed -n 's/^Architectures: //p' | grep -qw "$ARCHITECTURE"; then
	MIRROR="deb [signed-by=/usr/share/keyrings/debian-ports-archive-keyring.gpg] http://deb.debian.org/debian-ports $RELEASE main"
fi
if test "$ARCHITECTURE" = armel; then
	# Booting an armel kernel on qemu is next to impossible.
	ARCHITECTURE=armel,armhf
fi
if test "$ARCHITECTURE" = i386; then
	case "$RELEASE" in
		jessie|stretch|buster|bullseye|bookworm)
		;;
		*)
			# i386 no longer has a kernel
			ARCHITECTURE=i386,amd64
		;;
	esac
fi
case "$RELEASE" in
	jessie|stretch)
		MIRROR=http://archive.debian.org/debian
	;;
esac
set -- -- --architectures="$ARCHITECTURE"
if test -z "$RELEASE"; then
	# The ordering of maybe-merged-usr and
	# copy-host-apt-sources-and-preferences is unfortunately the wrong way
	# round. Therefore, we make debvm-create skip it and pass it ourselves.
	# The final empty string is the mirror specification.
	set -- \
		--skip=usrmerge \
		"$@" \
		--hook-dir=/usr/share/mmdebstrap/hooks/copy-host-apt-sources-and-preferences \
		--hook-dir=/usr/share/mmdebstrap/hooks/file-mirror-automount \
		--hook-dir=/usr/share/mmdebstrap/hooks/maybe-merged-usr \
		""
elif test -n "$MIRROR"; then
	set -- "$@" "$MIRROR"
fi
debvm-create -k "$SSH_KEYPATH.pub" -o "$IMAGE" -r "$RELEASE" "$@"

# Work around qemu #1106792
export OMP_THREAD_LIMIT=1

SSH_PORT=2222
timeout 600s debvm-run -s "$SSH_PORT" -i "$IMAGE" &
set -- localhost
test "$RELEASE" = jessie && set -- -o PubkeyAcceptedKeyTypes=+ssh-rsa "$@"
debvm-waitssh -t 540 "$SSH_PORT"
run_ssh "$@" poweroff
wait

"$(dirname "$0")/shell_interaction.expect" -- debvm-run -i "$IMAGE"
