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

set -euo pipefail

MCAST_ADDR="230.0.0.1:1234"
MAC_ADDR="52:54:00:00:01:03"
DISK="node03.qcow2"
VNC_DISPLAY=":3"
SERIAL_LOG="node03-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 "Node03 VM is already running (PID: $(pgrep -f "qemu-system-x86_64.*$DISK"))"
    exit 1
fi

echo "Starting Node03 VM..."
echo "  MAC: $MAC_ADDR"
echo "  Multicast: $MCAST_ADDR"
echo "  VNC: $VNC_DISPLAY (port 5903)"
echo "  Serial log: $SERIAL_LOG"
echo "  Boot: PXE (network boot enabled)"

# Launch QEMU with:
# - 8 vCPUs, 16GB RAM (per T036 spec)
# - Multicast socket networking
# - VNC display
# - Serial console logging
# - PXE boot enabled via iPXE ROM

exec qemu-system-x86_64 \
  -name node03 \
  -machine type=q35,accel=kvm \
  -cpu host \
  -smp 8 \
  -m 16G \
  -drive file="$DISK",if=virtio,format=qcow2 \
  -netdev socket,mcast="$MCAST_ADDR",id=mcast0 \
  -device virtio-net-pci,netdev=mcast0,mac="$MAC_ADDR" \
  -boot order=n \
  -vnc "$VNC_DISPLAY" \
  -serial telnet:localhost:4443,server,nowait \
  -daemonize \
  -pidfile node03.pid

echo "Node03 VM started (PID: $(cat node03.pid))"
echo "Connect via VNC: vncviewer localhost:5903"
echo "Connect via Telnet: telnet localhost 4443"
echo "Serial log: tail -f $SERIAL_LOG"
