#!/usr/bin/env bash
# Quick HTTP probes against a running mugi_backend (SwiftUI / headless).
#
# Usage:
#   ./scripts/probe_backend.sh [PORT] [AUTH_TOKEN]
#
# Env (optional):
#   MUGI_BACKEND_PORT — default port if PORT not passed (default 8321)
#   MUGI_AUTH_TOKEN — used if AUTH_TOKEN not passed; if unset, skips authed checks
#
# Examples:
#   MUGI_AUTH_TOKEN=secret MUGI_BACKEND_PORT=8321 ./scripts/probe_backend.sh
#   ./scripts/probe_backend.sh 18766 devcurltest
#
set -euo pipefail

PORT="${1:-${MUGI_BACKEND_PORT:-8321}}"
BASE="http://127.0.0.1:${PORT}"
TOKEN="${2:-${MUGI_AUTH_TOKEN:-}}"

fail() {
  echo "probe_backend: $*" >&2
  exit 1
}

echo "Probing ${BASE} ..."

# Unauthenticated health (must work for monitors)
code="$(curl -sS -o /tmp/mugi_probe_health.json -w '%{http_code}' "${BASE}/health" || true)"
[[ "$code" == "200" ]] || fail "GET /health expected HTTP 200, got ${code}"
grep -q '"ok"[[:space:]]*:[[:space:]]*true' /tmp/mugi_probe_health.json || fail "GET /health body missing ok:true"
echo "  OK GET /health"

# Mesh status without token → forbidden when auth is enabled
code_na="$(curl -sS -o /tmp/mugi_probe_mesh_na.json -w '%{http_code}' "${BASE}/mesh/status" || true)"
if [[ "$code_na" == "200" ]]; then
  echo "  OK GET /mesh/status (no auth — server has no token)"
elif [[ "$code_na" == "403" ]]; then
  echo "  OK GET /mesh/status without token → 403 (auth on)"
else
  fail "GET /mesh/status (no auth) unexpected HTTP ${code_na}"
fi

if [[ -n "$TOKEN" ]]; then
  code_m="$(curl -sS -o /tmp/mugi_probe_mesh.json -w '%{http_code}' \
    -H "X-Auth-Token: ${TOKEN}" "${BASE}/mesh/status" || true)"
  [[ "$code_m" == "200" ]] || fail "GET /mesh/status with token expected HTTP 200, got ${code_m}"
  grep -q '"hostname"' /tmp/mugi_probe_mesh.json || fail "GET /mesh/status body missing hostname"
  echo "  OK GET /mesh/status (authenticated)"

  code_p="$(curl -sS -o /tmp/mugi_probe_prefs.json -w '%{http_code}' \
    -H "X-Auth-Token: ${TOKEN}" "${BASE}/preferences" || true)"
  [[ "$code_p" == "200" ]] || fail "GET /preferences expected HTTP 200, got ${code_p}"
  echo "  OK GET /preferences (authenticated)"
else
  echo "  SKIP authenticated routes (set MUGI_AUTH_TOKEN or pass token as 2nd arg)"
fi

echo "probe_backend: all checks passed"
exit 0
