#!/bin/sh
# Read-only preflight checks for bhyve readiness and host baseline.

set -eu

PASS=0
WARN=0
FAIL=0

mark_pass() { PASS=$((PASS + 1)); echo "PASS: $1"; }
mark_warn() { WARN=$((WARN + 1)); echo "WARN: $1"; }
mark_fail() { FAIL=$((FAIL + 1)); echo "FAIL: $1"; }

have_cmd() { command -v "$1" >/dev/null 2>&1; }

check_cmd() {
  if have_cmd "$1"; then
    mark_pass "command available: $1"
  else
    mark_warn "command missing: $1"
  fi
}

check_file_contains() {
  _file="$1"
  _pattern="$2"
  _label="$3"

  if [ ! -f "$_file" ]; then
    mark_warn "$_label: missing $_file"
    return 0
  fi

  if grep -Eq "$_pattern" "$_file"; then
    mark_pass "$_label: $_file has $_pattern"
  else
    mark_warn "$_label: $_file missing $_pattern"
  fi
}

echo "==> Clawdie ISO host preflight (read-only)"

# Core command availability
check_cmd bhyve
check_cmd bhyvectl
check_cmd ifconfig
check_cmd sysctl
check_cmd kldstat

# vmm module and device nodes
if have_cmd kldstat && kldstat | grep -q 'vmm'; then
  mark_pass "vmm module loaded"
else
  mark_warn "vmm module not loaded (kldstat)"
fi

if [ -c /dev/vmmctl ]; then
  mark_pass "/dev/vmmctl exists"
else
  mark_warn "/dev/vmmctl missing"
fi

if [ -d /dev/vmm ]; then
  mark_pass "/dev/vmm directory exists (VM nodes)"
else
  mark_warn "/dev/vmm directory missing (no VMs created yet)"
fi

# Optional modules for bhyve tooling
if have_cmd kldstat && kldstat | grep -q 'if_tap'; then
  mark_pass "if_tap module loaded"
else
  mark_warn "if_tap module not loaded"
fi

if have_cmd kldstat && kldstat | grep -q 'nmdm'; then
  mark_pass "nmdm module loaded"
else
  mark_warn "nmdm module not loaded"
fi

# Loader config checks
check_file_contains /boot/loader.conf 'vmm_load="YES"' "loader"
check_file_contains /boot/loader.conf.local 'vmm_load="YES"' "loader.local"
check_file_contains /boot/loader.conf 'if_tap_load="YES"' "loader"
check_file_contains /boot/loader.conf.local 'if_tap_load="YES"' "loader.local"
check_file_contains /boot/loader.conf 'nmdm_load="YES"' "loader"
check_file_contains /boot/loader.conf.local 'nmdm_load="YES"' "loader.local"

# rc.conf checks
check_file_contains /etc/rc.conf 'cloned_interfaces=".*"' "rc.conf"
check_file_contains /etc/rc.conf 'ifconfig_warden0=' "rc.conf"

# Bridge state
if have_cmd ifconfig && ifconfig -l | grep -qw warden0; then
  mark_pass "warden0 bridge present"
  ifconfig warden0 >/dev/null 2>&1 || mark_warn "warden0 exists but could not query"
else
  mark_warn "warden0 bridge missing"
fi

# CPU virtualization capabilities
if have_cmd sysctl && sysctl -n hw.vmm >/dev/null 2>&1; then
  mark_pass "hw.vmm sysctl present"
else
  mark_warn "hw.vmm sysctl missing"
fi

echo "==> Summary: ${PASS} pass, ${WARN} warn, ${FAIL} fail"

if [ "$FAIL" -gt 0 ]; then
  exit 1
fi
