#!/usr/bin/env bash
# PXE Server VM Launch Script
# Connects to multicast socket network 230.0.0.1:1234

set -euo pipefail

MCAST_ADDR="230.0.0.1:1234"
MAC_ADDR="52:54:00:00:00:01"
DISK="pxe-server.qcow2"
VNC_DISPLAY=":0"
SERIAL_LOG="pxe-server-serial.log"

# Check if disk exists
if [ ! -f "$DISK" ]; then
    echo "Error: Disk image $DISK not found"
    exit 1
fi

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

echo "Starting PXE Server VM..."
echo "  MAC: $MAC_ADDR"
echo "  Multicast: $MCAST_ADDR"
echo "  VNC: $VNC_DISPLAY (port 5900)"
echo "  Serial log: $SERIAL_LOG"

# Launch QEMU with:
# - 4 vCPUs, 4GB RAM
# - Multicast socket networking
# - VNC display for console
# - Serial console logging
# - User-mode networking for internet access (for initial bootstrap)

exec qemu-system-x86_64 \
  -name pxe-server \
  -machine type=q35,accel=kvm \
  -cpu host \
  -smp 4 \
  -m 4G \
  -drive file="$DISK",if=virtio,format=qcow2 \
  -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 \
  -pidfile pxe-server.pid

echo "PXE Server VM started (PID: $(cat pxe-server.pid))"
echo "Connect via VNC: vncviewer localhost:5900"
echo "Serial log: tail -f $SERIAL_LOG"
