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

# UltraCloud VM Cluster - Node 01 (VDE Networking)
# Uses VDE switch instead of multicast sockets

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DISK="${SCRIPT_DIR}/node01.qcow2"
MAC_MCAST="52:54:00:12:34:01"
MAC_SLIRP="52:54:00:aa:bb:01"
VDE_SOCK="/tmp/vde.sock"
SSH_PORT=2201
VNC_DISPLAY=":1"
SERIAL_LOG="${SCRIPT_DIR}/node01-serial.log"
OVMF_CODE="/run/libvirt/nix-ovmf/edk2-x86_64-code.fd"
EFIVARS="${SCRIPT_DIR}/node01-efivars.fd"

if [ ! -f "$DISK" ]; then
    echo "ERROR: Disk not found at $DISK"
    exit 1
fi

if [ ! -S "${VDE_SOCK}/ctl" ]; then
    echo "ERROR: VDE switch not running at ${VDE_SOCK}"
    exit 1
fi

echo "Launching node01 with VDE networking..."
echo "  Disk: ${DISK}"
echo "  eth0 (VDE): ${MAC_MCAST} @ ${VDE_SOCK}"
echo "  eth1 (SLIRP): ${MAC_SLIRP}, SSH on host:${SSH_PORT}"

exec qemu-system-x86_64 \
  -name node01 \
  -machine type=q35,accel=kvm \
  -cpu host \
  -smp 8 \
  -m 16G \
  -drive if=pflash,format=raw,readonly=on,file="${OVMF_CODE}" \
  -drive if=pflash,format=raw,file="${EFIVARS}" \
  -drive file="${DISK}",if=virtio,format=qcow2 \
  -boot c \
  -netdev vde,sock="${VDE_SOCK}",id=vde0 \
  -device virtio-net-pci,netdev=vde0,mac="${MAC_MCAST}" \
  -netdev user,id=user0,hostfwd=tcp::${SSH_PORT}-:22 \
  -device virtio-net-pci,netdev=user0,mac="${MAC_SLIRP}" \
  -vnc "${VNC_DISPLAY}" \
  -serial "file:${SERIAL_LOG}" \
  -daemonize
