#!/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 ''
case "$ARCHITECTURE" in
	# Booting an armel kernel on qemu is next to impossible.
	armel) ARCHITECTURE=armel,armhf ;;
esac
MIRROR=
case "$RELEASE" in
	jessie|stretch)
		MIRROR=http://archive.debian.org/debian
	;;
esac
debvm-create -k "$SSH_KEYPATH.pub" -o "$IMAGE" -r "$RELEASE" -- --architectures="$ARCHITECTURE" $MIRROR

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