#!/usr/bin/env bash
# Smoke test for the WireGuard write-bridge handler (clusev-wg.sh serve-request).
#
# Regression guard for two timeout bugs: under `set -euo pipefail` the handler MUST always reach
# _write_result and write run/wg-result-<id>.json — otherwise the dashboard waits ~30s and shows
# "Keine Antwort vom Host". Two ways it used to die before writing a result:
#   1. a non-matching field-extraction grep (e.g. an empty/absent endpoint) failing the pipeline;
#   2. an action helper calling require_setup -> die (exit) on a not-yet-configured tunnel.
# This test drives every action with minimal/empty-field payloads and asserts a result file appears.
# It does NOT need root or a real WireGuard install — failures are fine, a missing REPLY is not.
#
# Run:  bash docker/wg/serve-request.test.sh
set -euo pipefail

here="$(cd "$(dirname "$0")" && pwd)"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
mkdir -p "$work/run"

# Root-bypassed copy: neutralise need_root so the handler runs unprivileged in a temp CLUSEV_DIR.
sed 's/^need_root()/_test_need_root()/; s/^  need_root serve-request/  :/' "$here/clusev-wg.sh" > "$work/clusev-wg.sh"

reqs=(
  '{"id":"SETUPEMPTYENDP0001","action":"setup","at":1,"subnet":"10.99.0.0/24","port":"51820","endpoint":"","name":"client-1"}'
  '{"id":"ADDPEERMINIMAL0002","action":"add-peer","at":1,"name":"laptop"}'
  '{"id":"REMOVEPEERMINI0003","action":"remove-peer","at":1,"name":"laptop"}'
  '{"id":"GATEUPNOFIELDS0004","action":"gate-up","at":1}'
  '{"id":"GATEDOWNNOFLDS0005","action":"gate-down","at":1}'
  '{"id":"GATESSHONNOFLD0006","action":"gate-ssh-on","at":1}'
  '{"id":"GATESSHOFFNOFL0007","action":"gate-ssh-off","at":1}'
  '{"id":"SETENDPOINTONL0008","action":"set-endpoint","at":1,"endpoint":"1.2.3.4:51820"}'
  '{"id":"SETPORTONLYFLD0009","action":"set-port","at":1,"port":"51821"}'
  '{"id":"SETSUBNETONLYF0010","action":"set-subnet","at":1,"subnet":"10.98.0.0/24"}'
)

fail=0
for req in "${reqs[@]}"; do
  rm -f "$work/run/"wg-result-*.json "$work/run/wg-request.json"
  printf '%s\n' "$req" > "$work/run/wg-request.json"
  CLUSEV_DIR="$work" bash "$work/clusev-wg.sh" serve-request >/dev/null 2>&1 || true
  act="$(printf '%s' "$req" | grep -oE '"action":"[a-z-]+"' | sed 's/.*://; s/"//g')"
  if ls "$work/run/"wg-result-*.json >/dev/null 2>&1; then
    printf '  ok   %-13s wrote a result\n' "$act"
  else
    printf '  FAIL %-13s NO result (would time out)\n' "$act"; fail=1
  fi
done

if [ "$fail" = 0 ]; then echo "PASS — every action writes a result"; else echo "FAILED"; exit 1; fi
