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

# PXE Server VM Launch Script (NixOS ISO Boot)
# Boots from NixOS ISO for nixos-anywhere provisioning

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

MCAST_ADDR="230.0.0.1:1234"
MAC_MCAST="52:54:00:00:00:01"
DISK="pxe-server.qcow2"
ISO="isos/latest-nixos-minimal-x86_64-linux.iso"
VNC_DISPLAY=":0"
SERIAL_LOG="pxe-server-serial.log"

# Check if ISO exists
if [ ! -f "$ISO" ]; then
    echo "ERROR: NixOS ISO not found at $ISO"
    exit 1
fi

# Check if already running
if pgrep -f "qemu-system-x86_64.*pxe-server" > /dev/null; then
    echo "PXE server VM is already running"
    exit 1
fi

echo "Launching PXE Server VM with NixOS ISO..."
echo "  Disk: ${DISK}"
echo "  ISO: ${ISO}"
echo "  MAC (multicast): ${MAC_MCAST}"
echo "  Multicast: ${MCAST_ADDR}"
echo "  VNC: ${VNC_DISPLAY} (port 5900)"
echo "  Serial log: ${SERIAL_LOG}"
echo ""
echo "After boot, configure static IP manually in installer:"
echo "  ip addr add 192.168.100.1/24 dev eth0"
echo "  ip link set eth0 up"
echo ""
echo "Then run nixos-anywhere from host:"
echo "  nixos-anywhere --flake .#pxe-server root@192.168.100.1"
echo ""

exec qemu-system-x86_64 \
  -name pxe-server \
  -machine type=q35,accel=kvm \
  -cpu host \
  -smp 2 \
  -m 2G \
  -drive file="${DISK}",if=virtio,format=qcow2 \
  -cdrom "${ISO}" \
  -boot d \
  -netdev socket,mcast="${MCAST_ADDR}",id=mcast0 \
  -device virtio-net-pci,netdev=mcast0,mac="${MAC_MCAST}" \
  -netdev user,id=user0 \
  -device virtio-net-pci,netdev=user0 \
  -vnc "${VNC_DISPLAY}" \
  -serial "file:${SERIAL_LOG}" \
  -daemonize
