#!/bin/bash
# Test Archipelago ISO in QEMU

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ISO="${1:-$SCRIPT_DIR/results/archipelago-debian-12-x86_64.iso}"

if [ ! -f "$ISO" ]; then
    echo "❌ ISO not found: $ISO"
    echo ""
    echo "Usage: $0 [path-to-iso]"
    echo ""
    echo "Build the ISO first with: ./build-debian-iso.sh"
    exit 1
fi

echo "🧪 Testing Archipelago ISO in QEMU"
echo "📀 ISO: $ISO"
echo "💾 RAM: 4GB"
echo "🖥️  CPU: 2 cores"
echo ""
echo "Press Ctrl+Alt+G to release mouse/keyboard from VM"
echo "Press Ctrl+C in this terminal to stop VM"
echo ""

# Create test disk if it doesn't exist
DISK="/tmp/archipelago-test-disk.qcow2"
if [ ! -f "$DISK" ]; then
    echo "Creating test disk..."
    qemu-img create -f qcow2 "$DISK" 20G
fi

echo "Starting VM in 3 seconds..."
sleep 3

# Run QEMU with UEFI (more modern, matches real hardware)
if [ -f "/opt/homebrew/share/qemu/edk2-x86_64-code.fd" ]; then
    # macOS with Homebrew QEMU
    OVMF="/opt/homebrew/share/qemu/edk2-x86_64-code.fd"
elif [ -f "/usr/share/OVMF/OVMF_CODE.fd" ]; then
    # Linux with OVMF
    OVMF="/usr/share/OVMF/OVMF_CODE.fd"
else
    # Fall back to legacy BIOS
    echo "⚠️  UEFI firmware not found, using legacy BIOS..."
    qemu-system-x86_64 \
        -machine pc \
        -m 4G \
        -smp 2 \
        -boot d \
        -cdrom "$ISO" \
        -drive if=virtio,format=qcow2,file="$DISK" \
        -net nic,model=virtio -net user,hostfwd=tcp::2222-:22,hostfwd=tcp::8100-:8100 \
        -vga virtio \
        -display default
    exit 0
fi

# UEFI boot
qemu-system-x86_64 \
    -machine q35 \
    -bios "$OVMF" \
    -m 4G \
    -smp 2 \
    -boot d \
    -cdrom "$ISO" \
    -drive if=virtio,format=qcow2,file="$DISK" \
    -net nic,model=virtio -net user,hostfwd=tcp::2222-:22,hostfwd=tcp::8100-:8100 \
    -vga virtio \
    -display default
