#!/bin/bash
# boot-test-solaris.sh
# Boots the already-installed disk directly (no ISO attached) inside nested QEMU,
# so you can confirm the install is actually bootable before rebooting the real
# server from Hetzner Cloud Console.
#
# Run from inside the Hetzner RESCUE system.
#
# Usage:
#   chmod +x boot-test-solaris.sh
#   ./boot-test-solaris.sh
#
# Connect via VNC on port 5901 (tunnel over SSH):
#   ssh -L 5901:localhost:5901 root@<rescue-ip>

set -euo pipefail

DISK="/dev/sda"
RAM_MB=4096
CPUS=2
VNC_DISPLAY=":1"

if [ "$(id -u)" -ne 0 ]; then
    echo "ERROR: must be run as root."
    exit 1
fi

if [ ! -b "$DISK" ]; then
    echo "ERROR: $DISK not found."
    lsblk
    exit 1
fi

KVM_FLAG=""
if [ -e /dev/kvm ]; then
    KVM_FLAG="-enable-kvm -cpu host"
else
    echo "WARNING: /dev/kvm not found, using software emulation (slow)."
    KVM_FLAG="-cpu qemu64"
fi

echo "Booting $DISK directly (no ISO) via q35 + ich9-ahci, cache=writethrough."
echo "VNC on $VNC_DISPLAY. Connect via your existing SSH tunnel to port 5901."
echo
echo "To exit cleanly when done: Ctrl+Alt+2 in the VNC window for the QEMU"
echo "monitor, then type 'quit' and press Enter."
echo
sleep 3

qemu-system-x86_64 \
    $KVM_FLAG \
    -machine q35 \
    -m "$RAM_MB" \
    -smp "$CPUS" \
    -drive file="$DISK",if=none,id=disk0,format=raw,cache=writethrough \
    -device ich9-ahci,id=ahci0 \
    -device ide-hd,drive=disk0,bus=ahci0.0 \
    -vnc "$VNC_DISPLAY" \
    -name "solaris-boot-test"

echo
echo "=== QEMU session ended ==="
