#!/bin/sh
# Copyright 2022 Jochen Sprickerhof <debvm@jochen.sprickerhof.de>
# SPDX-License-Identifier: MIT
#
# apt install e2fsprogs genext2fs mmdebstrap openssh-client qemu-kvm

set -x

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

SSH_KEYPATH=ssh_id

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

trap cleanup EXIT INT TERM QUIT

cat > upgrade << "EOF"
#!/bin/sh

set -ex

export DEBIAN_FRONTEND=noninteractive

sed -i "s/\([^ ]*\) \([^ ]*\) [^ ]* \(.*\)/\1 \2 $1 \3/" /etc/apt/sources.list
apt update
apt dist-upgrade -y

test "$1" = stretch && apt install libnss-resolve

apt autoremove --purge -y
apt clean
poweroff
EOF

chmod +x upgrade
ssh-keygen -f "$SSH_KEYPATH" -N ''

debvm-create --sshkey="$SSH_KEYPATH.pub" -r jessie --size=3G -- --customize-hook="copy-in upgrade /usr/local/bin"

SSH_PORT=2222
for RELEASE in stretch buster bullseye bookworm sid; do
	timeout 15m debvm-run -s "$SSH_PORT" &
	set -- localhost
	test "$RELEASE" = stretch && set -- -o PubkeyAcceptedKeyTypes=+ssh-rsa "$@"
	debvm-waitssh -t 150 "$SSH_PORT"
	run_ssh "$@" "upgrade $RELEASE"
	wait
done

timeout 5m debvm-run -s "$SSH_PORT" &
debvm-waitssh -t 150 "$SSH_PORT"
run_ssh localhost poweroff
wait
