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

# UltraCloud VM Cluster - Node 02 (Alpine Bootstrap)
# Features:
#   - Alpine virt ISO for automated SSH setup
#   - Multicast socket for inter-VM L2 communication (eth0)
#   - SLIRP with SSH port forward for host access (eth1)
#   - Telnet serial console (no VNC required)
#   - Automated SSH configuration via serial console

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DISK="${SCRIPT_DIR}/node02.qcow2"
ISO="${SCRIPT_DIR}/isos/alpine-virt-3.21.0-x86_64.iso"

# Networking
MAC_MCAST="52:54:00:12:34:02"        # eth0: multicast (192.168.100.12)
MAC_SLIRP="52:54:00:aa:bb:02"        # eth1: SLIRP DHCP (10.0.2.15)
MCAST_ADDR="230.0.0.1:1234"
SSH_PORT=2202                        # Host port -> VM port 22

# Console access
VNC_DISPLAY=":2"                     # VNC fallback
SERIAL_PORT=4402                     # Telnet serial

# Verify ISO exists
if [ ! -f "$ISO" ]; then
    echo "ERROR: Alpine virt ISO not found at $ISO"
    exit 1
fi

echo "============================================"
echo "Launching node02 with Alpine bootstrap..."
echo "============================================"
echo "  Disk: ${DISK}"
echo "  ISO: ${ISO}"
echo ""
echo "Network interfaces:"
echo "  eth0 (mcast):  MAC ${MAC_MCAST} -> configure 192.168.100.12"
echo "  eth1 (SLIRP):  MAC ${MAC_SLIRP} -> DHCP (10.0.2.x), SSH on host:${SSH_PORT}"
echo ""
echo "Console access:"
echo "  Serial: telnet localhost ${SERIAL_PORT}"
echo "  VNC:    vncviewer localhost${VNC_DISPLAY} (port 5902)"
echo ""
echo "Alpine setup automation:"
echo "  1. Boot Alpine (auto-login on console)"
echo "  2. Configure SSH via serial console"
echo "  3. SSH becomes available on host:${SSH_PORT}"
echo "  4. Run nixos-anywhere to install NixOS"
echo "============================================"

qemu-system-x86_64 \
  -name node02-alpine \
  -machine type=q35,accel=kvm \
  -cpu host \
  -smp 8 \
  -m 16G \
  -drive file="${DISK}",if=virtio,format=qcow2 \
  -cdrom "${ISO}" \
  -boot d \
  -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 mon:telnet:127.0.0.1:${SERIAL_PORT},server,nowait \
  -daemonize

echo ""
echo "VM started! Next steps:"
echo "  1. Wait 30s for Alpine boot"
echo "  2. Connect: telnet localhost ${SERIAL_PORT}"
echo "  3. Login as root (press Enter for password)"
echo "  4. Run SSH setup commands (see docs)"
echo ""
