#!/bin/sh
# SPDX-FileCopyrightText: 2022-2023 Jochen Sprickerhof <debvm@jochen.sprickerhof.de>
# SPDX-FileCopyrightText: 2022-2025 Helmut Grohne <helmut@subdivi.de>
# SPDX-License-Identifier: MIT
#
# apt install e2fsprogs 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

case "$1" in
	jessie|stretch) MIRROR="http://archive.debian.org/debian" ;;
	*) MIRROR="http://deb.debian.org/debian" ;;
esac
echo "deb $MIRROR $1 main" > /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" http://archive.debian.org/debian

# Work around qemu #1106792
export OMP_THREAD_LIMIT=1

SSH_PORT=2222
for RELEASE in stretch buster bullseye bookworm trixie 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
