#!/usr/bin/env bash
# tests/opnsense-build-config-iso/run-tests.sh -- offline harness for
# scripts/opnsense-build-config-iso.sh. Only tests the guard clauses this
# environment can actually exercise. Whether the built ISO is actually
# picked up by OPNsense's Configuration Importer is UNTESTED here (no
# genisoimage/xorriso and no real OPNsense VM were available this session)
# -- logged as residual risk, not hidden; see opentofu/README.md.
# Exit: 0 all pass | 1 any case failed.  ASCII + LF.
set -uo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SCRIPT="$HERE/../../scripts/opnsense-build-config-iso.sh"
PASS=0; FAIL=0

run() { # run <want_rc> <regex> <label> -- args...
  local want="$1" rx="$2" label="$3"; shift 3
  local out rc
  out="$(bash "$SCRIPT" "$@" 2>&1)"; rc=$?
  if [[ "$rc" == "$want" ]] && grep -qE "$rx" <<<"$out"; then
    echo "  PASS  $label"; PASS=$((PASS+1))
  else
    echo "  FAIL  $label (rc=$rc want=$want)"; echo "$out" | sed 's/^/        /'; FAIL=$((FAIL+1))
  fi
}

TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT

run 1 'usage: opnsense-build-config-iso.sh' "T1 missing all args FAILS (rc 1)"
run 1 'cannot read' "T2 nonexistent config.xml FAILS (rc 1)" "$TMP/does-not-exist.xml" "$TMP/out.iso"

echo '<opnsense></opnsense>' > "$TMP/config.xml"
if command -v genisoimage >/dev/null 2>&1 || command -v xorriso >/dev/null 2>&1; then
  echo "  SKIP  T3 genisoimage/xorriso-missing case (one IS present in this environment -- can't exercise the missing-tool guard here)"
else
  run 2 'genisoimage or xorriso required' "T3 no ISO tool available FAILS (rc 2)" "$TMP/config.xml" "$TMP/out.iso"
fi

echo; echo "RESULT: PASS=$PASS FAIL=$FAIL"
[[ "$FAIL" -eq 0 ]] && { echo "ALL PASS"; exit 0; } || exit 1
