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

# Nested KVM quick validator for PlasmaVMC host and guest
# Usage: sudo ./scripts/nested-kvm-check.sh

require_root() {
  if [[ "$EUID" -ne 0 ]]; then
    echo "[ERROR] Run as root (needed to read module params)" >&2
    exit 1
  fi
}

param_path() {
  if [[ -f /sys/module/kvm_intel/parameters/nested ]]; then
    echo "/sys/module/kvm_intel/parameters/nested"
  elif [[ -f /sys/module/kvm_amd/parameters/nested ]]; then
    echo "/sys/module/kvm_amd/parameters/nested"
  else
    echo ""
  fi
}

print_status() {
  local path="$1"
  local val
  val="$(<"$path")"
  echo "[INFO] Nested param at $path = $val"
  if [[ "$val" =~ ^[Yy1]$ ]]; then
    echo "[OK] Nested virtualization enabled"
  else
    echo "[WARN] Nested virtualization disabled. Enable via NixOS:"
    if [[ "$path" == *kvm_intel* ]]; then
      cat <<'CFG'
boot.kernelModules = [ "kvm-intel" ];
boot.extraModprobeConfig = ''
  options kvm-intel nested=1
'';
CFG
    else
      cat <<'CFG'
boot.kernelModules = [ "kvm-amd" ];
boot.extraModprobeConfig = ''
  options kvm-amd nested=1
'';
CFG
    fi
  fi
}

smoke_guest_kvm() {
  if ! command -v qemu-system-x86_64 >/dev/null 2>&1; then
    echo "[WARN] qemu-system-x86_64 not found; skip guest KVM smoke" >&2
    return
  fi
  echo "[INFO] Launching minimal nested guest kernel (non-interactive)..."
  set +e
  qemu-system-x86_64 -accel kvm -cpu host -m 256 -nographic \
    -kernel /run/current-system/kernel -append "console=ttyS0 panic=1" < /dev/null >/tmp/nested-kvm.log 2>&1 &
  local pid=$!
  sleep 5
  if ps -p $pid >/dev/null 2>&1; then
    echo "[OK] Nested KVM guest boot appears running (PID $pid). Stopping..."
    kill $pid >/dev/null 2>&1 || true
  else
    echo "[WARN] Nested guest did not stay running; check /tmp/nested-kvm.log" >&2
  fi
  set -e
}

main() {
  require_root
  local p
  p=$(param_path)
  if [[ -z "$p" ]]; then
    echo "[ERROR] No kvm_intel or kvm_amd module loaded; check virtualization support" >&2
    exit 1
  fi
  print_status "$p"
  smoke_guest_kvm
}

main "$@"
