#!/bin/bash

set -e

ISO="$1"
REUSE="$2"

if [ $# -eq 0 ]; then
  ISO=$(ls -t release/*.iso 2>/dev/null | gum choose --header "Select ISO to boot")
  if gum confirm --default=false "Reuse existing disk?"; then
    REUSE="reuse"
  fi
fi

if [ -z "$ISO" ]; then
  echo "Usage: omarchy-iso-boot [release/omarchy.iso] [reuse]"
  echo "  SSH available at: ssh -p 2222 root@localhost (after installing openssh)"
  exit 1
fi

omarchy-pkg-add qemu-full edk2-ovmf

if [[ -z ${WAYLAND_DISPLAY:-} && -z ${DISPLAY:-} ]]; then
  while IFS='=' read -r name value; do
    case "$name" in
      WAYLAND_DISPLAY|DISPLAY|XAUTHORITY|XDG_SESSION_TYPE)
        export "$name=$value"
        ;;
    esac
  done < <(systemctl --user show-environment 2>/dev/null || true)
fi

if [[ -z ${WAYLAND_DISPLAY:-} && -z ${DISPLAY:-} ]]; then
  echo "Unable to find a graphical session for QEMU." >&2
  echo "Run omarchy-iso-boot from the Omarchy desktop session." >&2
  exit 1
fi

DISK="/tmp/omarchy-iso-boot.qcow2"
if [[ ! -f $DISK || $REUSE != "reuse" ]]; then
  qemu-img create -f qcow2 "$DISK" 40G
  cp /usr/share/edk2/x64/OVMF_VARS.4m.fd /tmp/OVMF_VARS.4m.fd
fi

# Boot from ISO before we've installed, then boot from drive after
qemu-system-x86_64 \
  -cpu host -enable-kvm -machine q35,accel=kvm \
  -smp "$(nproc)" \
  -m 8192 \
  -drive if=pflash,format=raw,readonly=on,file=/usr/share/edk2/x64/OVMF_CODE.4m.fd \
  -drive if=pflash,format=raw,file=/tmp/OVMF_VARS.4m.fd \
  -drive file="$DISK",format=qcow2,if=none,id=drive0 \
  -device virtio-blk-pci,drive=drive0,bootindex=1 \
  -drive file="$ISO",media=cdrom,if=none,format=raw,id=cdrom0 \
  -device ide-cd,drive=cdrom0,bootindex=2 \
  -device virtio-vga-gl \
  -display sdl,gl=on \
  -usb -device usb-tablet \
  -netdev user,id=net0,hostfwd=tcp::2222-:22 \
  -device virtio-net-pci,netdev=net0 \
  -boot menu=on
