#!/usr/bin/env bash
# scripts/prereqs/check-prereqs.sh
#
# Read-only prereq report for the VR1 dc-dc workflow -- run this first on any new
# workstation/workspace to see what is missing before starting a stage. Mutates
# NOTHING. Each REQUIRED miss has a matching scripts/prereqs/install-*.sh.
#
# Exit: 0 all REQUIRED present | 1 one or more REQUIRED missing. ASCII + LF.
set -uo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
. "$HERE/lib-prereq.sh"

miss=0
line() { # <status> <label> <detail> <fixer>
  printf '  [%-7s] %-22s %s\n' "$1" "$2" "$3"
  if [ -n "${4:-}" ]; then printf '             fix: %s\n' "$4"; fi
  return 0   # MUST return 0: callers use `pq_have X && line OK.. || line WARN..`
}

echo "== VR1 dc-dc prereq report ($(hostname)) =="

# tofu >= 1.6.0 (REQUIRED, Stage 1-6)
if pq_have tofu; then
  v="$(tofu version 2>/dev/null | head -n1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -n1)"
  if [ "$(printf '1.6.0\n%s\n' "$v" | sort -V | head -n1)" = "1.6.0" ]; then
    line OK tofu "$v"
  else
    line OLD tofu "${v:-unknown} < 1.6.0" "bash scripts/prereqs/install-opentofu.sh"; miss=1
  fi
else
  line MISSING tofu "not on PATH" "bash scripts/prereqs/install-opentofu.sh"; miss=1
fi

# virsh / libvirt (REQUIRED, Stage 1+)
if pq_have virsh; then line OK virsh "$(virsh --version 2>/dev/null)"
else line MISSING virsh "libvirt not installed" "bash scripts/prereqs/install-virtualization.sh"; miss=1; fi
if id -nG 2>/dev/null | tr ' ' '\n' | grep -qx libvirt; then line OK libvirt-group "user in libvirt group"
else line MISSING libvirt-group "user not in libvirt group" "bash scripts/prereqs/install-virtualization.sh (then re-login)"; miss=1; fi

# jq (REQUIRED, many ops scripts)
if pq_have jq; then line OK jq "$(jq --version 2>/dev/null)"
else line MISSING jq "JSON processor absent" "bash scripts/prereqs/install-jq.sh"; miss=1; fi

# image tools (REQUIRED for Stage 2/3 OPNsense build)
if pq_have qemu-img; then line OK qemu-img "present"
else line MISSING qemu-img "qemu-utils absent" "bash scripts/prereqs/install-image-tools.sh"; miss=1; fi
if pq_have xorriso || pq_have genisoimage; then line OK iso-builder "$(pq_have xorriso && echo xorriso || echo genisoimage)"
else line MISSING iso-builder "no ISO9660 builder" "bash scripts/prereqs/install-image-tools.sh"; miss=1; fi

# near-universal, reported but not auto-installed here
pq_have curl    && line OK curl    "present" || line WARN curl    "absent (needed for tofu init + downloads)"
pq_have python3 && line OK python3 "$(python3 --version 2>/dev/null)" || line WARN python3 "absent (netbox + provider-bundle-check)"
pq_have sudo    && line OK sudo    "present" || line WARN sudo    "absent (installers need root)"

echo
if [ "$miss" -eq 0 ]; then echo "PREREQS: all required present"; exit 0; fi
echo "PREREQS: missing required tooling (see 'fix:' lines, or run scripts/prereqs/install-all.sh)"; exit 1
