#!/usr/bin/env bash
# tests/opnsense-prep-image/run-tests.sh -- offline harness for
# scripts/opnsense-prep-image.sh. Only tests the guard clauses this
# environment can actually exercise -- no network fetch of a real OPNsense
# image is attempted (that's out of scope for an offline harness; the
# download/convert path itself is UNTESTED here, logged not hidden).
# Exit: 0 all pass | 1 any case failed.  ASCII + LF.
set -uo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SCRIPT="$HERE/../../scripts/opnsense-prep-image.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
}

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

run 1 'usage: opnsense-prep-image.sh' "T1 missing all args FAILS (rc 1)"
run 1 'usage: opnsense-prep-image.sh' "T2 missing output-path arg FAILS (rc 1)" "26.1"

unset OPNSENSE_MIRROR_BASE
run 1 'OPNSENSE_MIRROR_BASE' "T3 OPNSENSE_MIRROR_BASE unset FAILS (rc 1)" "26.1" "$TMPOUT/out.qcow2"

# T3b: the script must survive being PIPED (`bash -s`), where BASH_SOURCE is unset under
# `set -u` -- it died on `BASH_SOURCE[0]: unbound variable` before its first guard when
# shipped via `ssh 'bash -s'` on the dc1 build (2026-07-22 queued finding). The correct
# behavior piped is IDENTICAL to T3: reach the mirror guard, not an unbound-variable death.
out="$(bash -s -- "26.1" "$TMPOUT/out.qcow2" < "$SCRIPT" 2>&1)"; rc=$?
if [[ "$rc" == "1" ]] && grep -q 'OPNSENSE_MIRROR_BASE' <<<"$out" && ! grep -q 'unbound variable' <<<"$out"; then
  echo "  PASS  T3b piped (bash -s) reaches the mirror guard, no BASH_SOURCE death"; PASS=$((PASS+1))
else
  echo "  FAIL  T3b piped (bash -s) run (rc=$rc)"; echo "$out" | sed 's/^/        /'; FAIL=$((FAIL+1))
fi

if command -v qemu-img >/dev/null 2>&1; then
  echo "  SKIP  T4 qemu-img-missing case (qemu-img IS present in this environment -- can't exercise the missing-binary guard here)"
else
  export OPNSENSE_MIRROR_BASE="https://example.invalid/opnsense"
  run 2 'qemu-img required' "T4 qemu-img missing FAILS (rc 2)" "26.1" "$TMPOUT/out.qcow2"
  unset OPNSENSE_MIRROR_BASE
fi

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