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

# UltraCloud VM Cluster - Node 02 (Recovery Boot)
# Boots from disk using new kernel/initrd from nix store

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DISK="${SCRIPT_DIR}/node02.qcow2"
MAC_MCAST="52:54:00:12:34:02"
MAC_SLIRP="52:54:00:aa:bb:02"
MCAST_ADDR="230.0.0.1:1234"
SSH_PORT=2202
VNC_DISPLAY=":2"
SERIAL_LOG="${SCRIPT_DIR}/node02-serial.log"

# New kernel and initrd from built configuration
KERNEL="/nix/store/npjqdfy6j5nb9srbzj0cc2bw0a0gvqag-linux-6.12.61/bzImage"
INITRD="/nix/store/s4vr2i8vyyggrrybgk3afdyvzxhkm365-initrd-linux-6.12.61/initrd"
KERNEL_PARAMS="net.ifnames=0 biosdevname=0 console=ttyS0,115200n8 loglevel=4 root=fstab loglevel=4 lsm=landlock,yama,bpf"

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

echo "Launching node02 in recovery mode..."
echo "  Disk: ${DISK}"
echo "  Kernel: ${KERNEL}"
echo "  Initrd: ${INITRD}"
echo "  eth0 (multicast): ${MAC_MCAST} @ ${MCAST_ADDR}"
echo "  eth1 (SLIRP): ${MAC_SLIRP}, SSH on host:${SSH_PORT}"
echo "  VNC: ${VNC_DISPLAY} (port 5902)"
echo "  Serial log: ${SERIAL_LOG}"

exec qemu-system-x86_64 \
  -name node02 \
  -machine type=q35,accel=kvm \
  -cpu host \
  -smp 8 \
  -m 16G \
  -drive file="${DISK}",if=virtio,format=qcow2 \
  -kernel "${KERNEL}" \
  -initrd "${INITRD}" \
  -append "${KERNEL_PARAMS}" \
  -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
