#!/bin/bash
cd "/Users/user/dev/hdmistat/qemu-ubuntu-test"

echo "Starting QEMU ARM64 Ubuntu with cloud-init..."
echo ""
echo "Login: ubuntu / ubuntu"
echo "SSH available on port 2223: ssh ubuntu@localhost -p 2223"
echo "VNC available on port 5902 (password: vncvnc)"
echo ""
echo "hdmistat will be installed automatically via cloud-init"
echo "Check cloud-init status with: cloud-init status"
echo ""
echo "Press Ctrl+A, X to quit"
echo ""

# Create fresh disk image from base image
echo "Creating fresh disk image..."
qemu-img create -f qcow2 -F qcow2 -b ubuntu-22.04-server-cloudimg-arm64.img hdmistat-test.qcow2 8G

# Find EFI firmware and vars
EFI_CODE=""
EFI_VARS=""
for dir in /nix/store/*/share/qemu /run/current-system/sw/share/qemu; do
    if [ -f "$dir/edk2-aarch64-code.fd" ]; then
        EFI_CODE="$dir/edk2-aarch64-code.fd"
        if [ -f "$dir/edk2-arm-vars.fd" ]; then
            EFI_VARS="$dir/edk2-arm-vars.fd"
        fi
        break
    fi
done

# Create a copy of EFI vars if found
if [ -n "$EFI_VARS" ] && [ ! -f "efivars.fd" ]; then
    cp "$EFI_VARS" efivars.fd
    chmod u+rw efivars.fd
fi

BIOS_ARGS=""
if [ -n "$EFI_CODE" ]; then
    # Use pflash method for UEFI boot (not -bios)
    BIOS_ARGS="-drive if=pflash,file=$EFI_CODE,format=raw,readonly=on"
    if [ -f "efivars.fd" ]; then
        BIOS_ARGS="$BIOS_ARGS -drive if=pflash,format=raw,file=efivars.fd"
    fi
fi

qemu-system-aarch64 \
    -M virt \
    -accel hvf \
    -cpu host \
    -smp 4 \
    -m 2G \
    -nographic \
    -object secret,id=vncsec0,data=vncvnc \
    -drive file=hdmistat-test.qcow2,format=qcow2,if=virtio \
    -drive file=cloud-init.iso,format=raw,if=virtio \
    -netdev user,id=net0,hostfwd=tcp::2223-:22 \
    -device virtio-net-pci,netdev=net0 \
    -device virtio-gpu-pci \
    -display default,show-cursor=on \
    -vnc :2,password-secret=vncsec0 \
    -serial mon:stdio \
    -virtfs local,path="/Users/user/dev/hdmistat",mount_tag=hdmistat,security_model=none,id=hdmistat \
    $BIOS_ARGS \
    ${@}

# Clean up disk image after QEMU exits
echo ""
echo "Cleaning up disk image for fresh start next time..."
rm -f hdmistat-test.qcow2
echo "Disk image removed. Next run will start fresh with cloud-init."
