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

# UltraCloud VM Cluster - Node 01 (Boot from installed NixOS on disk)
# UEFI boot with OVMF firmware

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

# UEFI firmware (OVMF)
OVMF_CODE="/nix/store/8ywkyiyc5cgrx72vrrf98mwbnnmix9a4-OVMF-202511-fd/FV/OVMF_CODE.fd"
OVMF_VARS_TEMPLATE="/nix/store/8ywkyiyc5cgrx72vrrf98mwbnnmix9a4-OVMF-202511-fd/FV/OVMF_VARS.fd"
OVMF_VARS="${SCRIPT_DIR}/node01-efivars.fd"

# Networking
MAC_MCAST="52:54:00:12:34:01"        # eth0: multicast cluster network
MAC_SLIRP="52:54:00:aa:bb:01"        # eth1: SLIRP for SSH access
SSH_PORT=2201                        # Host port -> VM port 22
MCAST_ADDR="230.0.0.1:1234"          # Multicast address for cluster

# Console access
VNC_DISPLAY=":1"                     # VNC fallback
SERIAL_LOG="${SCRIPT_DIR}/node01-serial.log"

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

# Create per-VM UEFI vars if not exists
if [ ! -f "$OVMF_VARS" ]; then
    echo "Creating UEFI vars file for node01..."
    cp "$OVMF_VARS_TEMPLATE" "$OVMF_VARS"
fi

echo "============================================"
echo "Launching node01 from disk (UEFI boot)..."
echo "============================================"
echo "  Disk:   ${DISK}"
echo "  UEFI:   ${OVMF_CODE}"
echo ""
echo "Network interfaces:"
echo "  eth0 (multicast): MAC ${MAC_MCAST}, ${MCAST_ADDR}"
echo "  eth1 (SLIRP):     MAC ${MAC_SLIRP}, SSH on host:${SSH_PORT}"
echo ""
echo "Console access:"
echo "  Serial: ${SERIAL_LOG}"
echo "  VNC:    vncviewer localhost${VNC_DISPLAY} (port 5901)"
echo "  SSH:    ssh -p ${SSH_PORT} root@localhost"
echo "============================================"

cd "${SCRIPT_DIR}"

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="${OVMF_VARS}" \
  -drive file="${DISK}",if=virtio,format=qcow2 \
  -netdev socket,mcast="${MCAST_ADDR}",id=mcast0 \
  -device virtio-net-pci,netdev=mcast0,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

echo "Node01 started successfully!"
echo "Wait 20-30 seconds for boot, then: ssh -p ${SSH_PORT} root@localhost"
