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

# UltraCloud VM Cluster - Node 03 (Boot from installed NixOS on disk)
# Boots from the NixOS installation created by nixos-anywhere

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DISK="${SCRIPT_DIR}/node03.qcow2"

# Networking
MAC_MCAST="52:54:00:12:34:03"        # eth0: multicast VDE
MAC_SLIRP="52:54:00:aa:bb:03"        # eth1: SLIRP DHCP (10.0.2.15)
SSH_PORT=2203                        # Host port -> VM port 22

# Console access
VNC_DISPLAY=":3"                     # VNC fallback
SERIAL_PORT=4403                     # Telnet serial

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

# Check if VDE switch is running
if ! pgrep -f "vde_switch.*vde.sock" > /dev/null; then
    echo "ERROR: VDE switch not running. Start with: vde_switch -sock /tmp/vde.sock -daemon"
    exit 1
fi

echo "============================================"
echo "Launching node03 from disk (installed NixOS)..."
echo "============================================"
echo "  Disk:   ${DISK}"
echo ""
echo "Network interfaces:"
echo "  eth0 (VDE):    MAC ${MAC_MCAST}"
echo "  eth1 (SLIRP):  MAC ${MAC_SLIRP}, SSH on host:${SSH_PORT}"
echo ""
echo "Console access:"
echo "  Serial: telnet localhost ${SERIAL_PORT}"
echo "  VNC:    vncviewer localhost${VNC_DISPLAY} (port 5903)"
echo "  SSH:    ssh -p ${SSH_PORT} root@localhost"
echo ""
echo "Boot: From disk (installed NixOS)"
echo "============================================"

cd "${SCRIPT_DIR}"

qemu-system-x86_64 \
  -name node03 \
  -machine type=q35,accel=kvm \
  -cpu host \
  -smp 4 \
  -m 4G \
  -drive file="${DISK}",if=virtio,format=qcow2 \
  -netdev vde,id=vde0,sock=/tmp/vde.sock \
  -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 mon:telnet:127.0.0.1:${SERIAL_PORT},server,nowait \
  -daemonize

echo "Node03 started successfully!"
echo "Wait 10-15 seconds for boot, then: ssh -p ${SSH_PORT} root@localhost"
