#!/bin/sh
# vm-test-boot.sh — boot the latest Mountaineer ISO in a fresh disposable
# target VM, NO install config attached. The live env comes up; ssh in
# on TARGET_SSH_PORT with the builder ed25519 key.
#
# Useful for poking at the live environment, verifying the apkovl
# applied, running `mountaineer-install --dry-run` interactively, etc.
#
# For the unattended install loop, use vm-test-install.sh.

. "$(dirname "$0")/common.sh"
ensure_dirs

ISO=$(ls -t "$ROOT/out"/*.iso 2>/dev/null | head -1 || true)
if [ -z "$ISO" ] || [ ! -f "$ISO" ]; then
    echo "error: no ISO found in $ROOT/out/. Run tools/qemu/vm-build.sh first." >&2
    exit 1
fi

TARGET_DISK="$DISK_DIR/target.qcow2"
TARGET_SIZE="${TARGET_SIZE:-20G}"
NVRAM="$NVRAM_DIR/target_VARS.fd"

# Fresh disk + NVRAM every run.
rm -f "$TARGET_DISK" "$NVRAM" "$VMS/target.pid"
qemu-img create -f qcow2 "$TARGET_DISK" "$TARGET_SIZE" >/dev/null
cp "$OVMF_VARS_TEMPLATE" "$NVRAM"

LOG="$VMS/logs/target-boot-serial.log"
MON="$VMS/sockets/target-mon.sock"
rm -f "$LOG" "$MON"

echo "==> booting target VM with $ISO (no install config)"
# shellcheck disable=SC2046,SC2086
qemu-system-x86_64 \
    -name target \
    -machine type=q35 \
    $ACCEL_ARGS \
    -cpu max -smp $SMP -m $MEM \
    -drive if=pflash,format=raw,readonly=on,file="$OVMF_CODE" \
    -drive if=pflash,format=raw,file="$NVRAM" \
    -drive file="$TARGET_DISK",if=virtio,format=qcow2 \
    -cdrom "$ISO" \
    -boot d \
    -netdev user,id=net0,hostfwd=tcp:127.0.0.1:$TARGET_SSH_PORT-:22 \
    -device virtio-net-pci,netdev=net0 \
    -device virtio-rng-pci \
    -display none \
    -serial file:"$LOG" \
    -monitor unix:"$MON",server,nowait \
    -daemonize \
    -pidfile "$VMS/target.pid"

echo "==> target VM running (pid $(cat $VMS/target.pid))"
echo "    serial log: $LOG"
echo "    ssh:        ssh -p $TARGET_SSH_PORT -i $KEYS_DIR/builder_ed25519 root@127.0.0.1"
echo "    stop:       printf 'quit\\n' | nc -U $MON"
echo ""
echo "==> waiting up to 5 min for sshd to come up on 127.0.0.1:$TARGET_SSH_PORT"
deadline=$(( $(date +%s) + 300 ))
while [ "$(date +%s)" -lt "$deadline" ]; do
    if ssh -p "$TARGET_SSH_PORT" \
        -i "$KEYS_DIR/builder_ed25519" \
        -o StrictHostKeyChecking=no \
        -o UserKnownHostsFile=/dev/null \
        -o ConnectTimeout=3 \
        -o BatchMode=yes \
        root@127.0.0.1 'true' 2>/dev/null; then
        echo "==> ssh ready"
        exit 0
    fi
    sleep 5
    printf '.'
done

echo ""
echo "warning: sshd not reachable in 5 min — check $LOG"
exit 1
