#!/usr/bin/env bash
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ISO_PATH="${ISO_PATH:-$REPO_ROOT/iso/live-image-amd64.hybrid.iso}"
HTTPS_PORT="${HTTPS_PORT:-2443}"
RELAY_PORT="${RELAY_PORT:-28888}"
CPUS="${CPUS:-2}"
MEM_MB="${MEM_MB:-2048}"

USE_UEFI="${USE_UEFI:-0}"
HEADLESS="${HEADLESS:-0}"

if [[ ! -f "$ISO_PATH" ]]; then
  echo "[run-iso] missing ISO: $ISO_PATH" >&2
  echo "[run-iso] build first: ./build.sh --clean" >&2
  exit 1
fi

if ! command -v qemu-system-x86_64 >/dev/null 2>&1; then
  echo "[run-iso] missing qemu-system-x86_64. Install: sudo apt-get install -y qemu-system-x86 ovmf" >&2
  exit 1
fi

QEMU_FW_ARGS=()
if [[ "$USE_UEFI" == "1" ]]; then
  if [[ -f /usr/share/ovmf/OVMF.fd ]]; then
    # Monolithic OVMF image (works with -bios)
    QEMU_FW_ARGS=(-bios /usr/share/ovmf/OVMF.fd)
  elif [[ -f /usr/share/OVMF/OVMF_CODE_4M.fd && -f /usr/share/OVMF/OVMF_VARS_4M.fd ]]; then
    # Split OVMF image (CODE + writable VARS)
    VARS_TMP="${TMPDIR:-/tmp}/n-os-tr-ovmf-vars-$$.fd"
    cp /usr/share/OVMF/OVMF_VARS_4M.fd "$VARS_TMP"
    QEMU_FW_ARGS=(
      -drive if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF_CODE_4M.fd
      -drive if=pflash,format=raw,file="$VARS_TMP"
    )
  else
    echo "[run-iso] no usable OVMF firmware found" >&2
    exit 1
  fi
fi

ACCEL_ARGS=()
if [[ -r /dev/kvm && -w /dev/kvm ]]; then
  ACCEL_ARGS=(-enable-kvm -machine q35,accel=kvm -cpu host)
else
  echo "[run-iso] /dev/kvm not accessible; using TCG emulation" >&2
  ACCEL_ARGS=(-machine q35,accel=tcg -cpu max)
fi

echo "[run-iso] booting: $ISO_PATH"
echo "[run-iso] firmware mode: $([[ "$USE_UEFI" == "1" ]] && echo uefi || echo bios)"
echo "[run-iso] host forwards: https://127.0.0.1:${HTTPS_PORT} -> guest:443, tcp://127.0.0.1:${RELAY_PORT} -> guest:8888"

EXTRA_DISPLAY_ARGS=()
if [[ "$HEADLESS" == "1" ]]; then
  echo "[run-iso] mode: headless serial (Ctrl-a x to quit, Ctrl-a c monitor)"
  EXTRA_DISPLAY_ARGS=(-nographic -serial mon:stdio)
else
  echo "[run-iso] mode: graphical window"
  EXTRA_DISPLAY_ARGS=()
fi

exec qemu-system-x86_64 \
  "${ACCEL_ARGS[@]}" \
  "${QEMU_FW_ARGS[@]}" \
  -boot order=d,menu=off \
  -smp "$CPUS" \
  -m "$MEM_MB" \
  -drive file="$ISO_PATH",format=raw,if=ide,media=cdrom,readonly=on \
  -netdev user,id=n0,hostfwd=tcp::${HTTPS_PORT}-:443,hostfwd=tcp::${RELAY_PORT}-:8888 \
  -device virtio-net-pci,netdev=n0 \
  "${EXTRA_DISPLAY_ARGS[@]}"
