#!/usr/bin/env bash

# Build the Nomarchy graphical live ISO and boot it in QEMU for a
# try-before-install experience. The ISO is the `nomarchy-live`
# NixOS configuration - same Nomarchy system + Home Manager stack as
# `nomarchy-test-vm`, just wrapped in an installable live medium.

set -e

echo "Building Nomarchy Live ISO..."
nix build .#nixosConfigurations.nomarchy-live.config.system.build.isoImage

ISO=$(ls -1 result/iso/*.iso 2>/dev/null | head -n 1)
if [ -z "$ISO" ]; then
    echo "Error: ISO build succeeded but no .iso file found in result/iso/"
    exit 1
fi

# Prefer UEFI with OVMF so the ISO boots the same way a modern install does.
# Fall back to BIOS if OVMF isn't available on this host.
OVMF_CANDIDATES=(
    "/run/current-system/sw/share/OVMF/OVMF_CODE.fd"
    "/run/current-system/sw/share/qemu/edk2-x86_64-code.fd"
    "/nix/var/nix/profiles/system/sw/share/OVMF/OVMF_CODE.fd"
    "/usr/share/OVMF/OVMF_CODE.fd"
)
BIOS_ARG=()
for c in "${OVMF_CANDIDATES[@]}"; do
    if [ -f "$c" ]; then
        # Use pflash for UEFI firmware. -bios is for legacy BIOS.
        BIOS_ARG=(-drive "if=pflash,format=raw,readonly=on,file=$c")

        # Optional: Add matching VARS file if it exists.
        VARS="${c%_CODE.fd}_VARS.fd"
        if [ -f "$VARS" ]; then
            BIOS_ARG+=(-drive "if=pflash,format=raw,readonly=on,file=$VARS")
        fi
        break
    fi
done

# KVM if the host supports it; software emulation otherwise.
ACCEL_ARG=()
if [ -r /dev/kvm ]; then
    ACCEL_ARG=(-enable-kvm -cpu host)
fi

echo "Launching ISO: $ISO"
exec qemu-system-x86_64 \
    "${ACCEL_ARG[@]}" \
    -m 4096 -smp 2 \
    "${BIOS_ARG[@]}" \
    -device virtio-vga-gl -display gtk,gl=on \
    -device virtio-net-pci,netdev=n0 -netdev user,id=n0 \
    -cdrom "$ISO" -boot d
