#!/usr/bin/env bash
# PXE Server VM Launch Script (Alpine Installation Mode)
# Boots from Alpine ISO to install the PXE server

set -euo pipefail

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

MCAST_ADDR="230.0.0.1:1234"
MAC_ADDR="52:54:00:00:00:01"
DISK="pxe-server.qcow2"
ISO="isos/alpine-virt-3.21.0-x86_64.iso"
VNC_DISPLAY=":0"
SERIAL_LOG="pxe-server-serial.log"

# Check if ISO exists
if [ ! -f "$ISO" ]; then
    echo "Error: ISO image $ISO not found"
    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 (PID: $(pgrep -f "qemu-system-x86_64.*pxe-server"))"
    exit 1
fi

echo "Starting PXE Server VM in installation mode..."
echo "  MAC (multicast): $MAC_ADDR"
echo "  Multicast network: $MCAST_ADDR"
echo "  ISO: $ISO"
echo "  VNC: $VNC_DISPLAY (port 5900)"
echo "  Serial log: $SERIAL_LOG"
echo ""
echo "After boot, login as root (no password) and run:"
echo "  setup-alpine"
echo ""

# Launch QEMU with:
# - 2 vCPUs, 2GB RAM
# - Multicast socket networking (for cluster nodes)
# - User-mode networking (for internet access during installation)
# - Boot from ISO
# - Serial console for logging

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_ADDR" \
  -netdev user,id=user0 \
  -device virtio-net-pci,netdev=user0 \
  -vnc "$VNC_DISPLAY" \
  -serial "file:$SERIAL_LOG" \
  -daemonize

echo "PXE Server VM started"
echo "Connect via VNC: vncviewer localhost:5900"
echo "Serial log: tail -f $SERIAL_LOG"
