#!/usr/bin/env bash
# UDP / WireGuard data-plane debug from a Linux laptop (task 4).
# HTTP control plane must work first (ra_e2e_cli.sh). See docs/REMOTE_ACCESS_VALIDATION.md
# and proposals Appendix 1.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
# shellcheck source=ra_lib.sh
source "$ROOT/scripts/ra_lib.sh"

WG_HOST="${WG_HOST:-ra.apps.f0xx.org}"
WG_PORT="${WG_PORT:-45340}"
BE_WG_IP="${BE_WG_IP:-172.200.2.1}"
DEVICE_ID="${RA_DEVICE_ID:-ra-udp-$(hostname -s | tr ' ' '-')}"
CONF="/tmp/ra-udp-${DEVICE_ID}.conf"
APPLY="${RA_UDP_APPLY:-0}"
SKIP_HTTP="${RA_UDP_SKIP_HTTP:-0}"

usage() {
  cat <<EOF
Usage: $0 [--apply] [--device-id ID] [--skip-http]

Env:
  CRASHES_BASE, ADMIN_USER, ADMIN_PASS  — operator API
  RA_DEVICE_ID, WG_HOST (default ra.apps.f0xx.org), WG_PORT (45340)
  BE_WG_IP (172.200.2.1)                — ping target on tunnel
  RA_UDP_APPLY=1                        — same as --apply (wg-quick up)

Steps: DNS → UDP port → optional HTTP E2E → connect JSON → wg conf → optional tunnel → ping

EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --apply) APPLY=1; shift ;;
    --device-id) DEVICE_ID="$2"; shift 2 ;;
    --skip-http) SKIP_HTTP=1; shift ;;
    -h|--help) usage; exit 0 ;;
    *) echo "Unknown: $1" >&2; usage; exit 2 ;;
  esac
done

export RA_DEVICE_ID="$DEVICE_ID"
export RA_RANDOM_FILE="/tmp/androidcast-ra-${DEVICE_ID}.random"

note() { echo "== $*"; }
ok() { echo "OK  $*"; }
warn() { echo "WARN $*"; }
fail() { echo "FAIL $*"; exit 1; }

note "RA UDP debug — device_id=$DEVICE_ID"
note "BASE=$(ra_base)"
note "WG endpoint ${WG_HOST}:${WG_PORT}"

note "1. DNS (CNAME chain)"
APPS_IP="$(dig +short apps.f0xx.org A 2>/dev/null | head -1)"
RA_IP="$(dig +short "$WG_HOST" A 2>/dev/null | head -1)"
echo "apps.f0xx.org A: ${APPS_IP:-?}"
echo "${WG_HOST} A: ${RA_IP:-?}"
if [[ -n "$APPS_IP" && -n "$RA_IP" && "$APPS_IP" == "$RA_IP" ]]; then
  ok "ra host resolves same as apps (CNAME OK)"
else
  warn "A records differ or missing — check CNAME/DNS"
fi

note "2. UDP reachability"
if command -v nc >/dev/null 2>&1; then
  if nc -zvu -w 3 "$WG_HOST" "$WG_PORT" 2>&1 | grep -qiE 'succeeded|open'; then
    ok "UDP ${WG_PORT} appears open (nc)"
  else
    warn "UDP ${WG_PORT} not confirmed open — FE DNAT / firewall?"
  fi
else
  warn "nc not found — skip UDP probe"
fi

if [[ "$SKIP_HTTP" -eq 0 ]]; then
  note "3. HTTP control plane (quick)"
  if CRASHES_BASE="$(ra_base)" bash "$ROOT/scripts/test_remote_access_api.sh" >/dev/null 2>&1; then
    ok "test_remote_access_api.sh"
  else
    warn "API smoke failed — fix HTTP before UDP"
  fi
else
  note "3. HTTP skipped"
fi

note "4. Operator: whitelist + open session (if not already)"
COOKIE_JAR="$(mktemp)"
trap 'rm -f "$COOKIE_JAR"; sudo wg-quick down "$CONF" 2>/dev/null || true' EXIT
ra_admin_login "$COOKIE_JAR"
ra_admin_post "$COOKIE_JAR" whitelist "{\"device_id\":\"$DEVICE_ID\",\"whitelisted\":true}" >/dev/null
ra_admin_post "$COOKIE_JAR" open_session "{\"device_id\":\"$DEVICE_ID\"}" >/dev/null
ok "whitelist + open_session"

note "5. Device poll → connect (may wait min_poll_interval_s)"
export RA_DEVICE_ID="$DEVICE_ID"
bash "$ROOT/scripts/ra_device_sim.sh" poll --until connect --device-id "$DEVICE_ID" --base "$(ra_base)" > /tmp/ra-udp-connect.json
grep -q '"action":"connect"' /tmp/ra-udp-connect.json || fail "no connect in response"
ok "heartbeat connect"

note "6. Build wg-quick config"
RESP="$(cat /tmp/ra-udp-connect.json)"
ra_wg_quick_from_connect "$RESP" >"$CONF"
echo "--- $CONF ---"
sed 's/PrivateKey = .*/PrivateKey = <redacted>/' "$CONF"
ok "wrote $CONF"

if [[ "$APPLY" -eq 1 ]]; then
  command -v wg-quick >/dev/null 2>&1 || fail "wg-quick not installed"
  note "7. Bring up tunnel"
  sudo wg-quick up "$CONF"
  sudo wg show
  note "8. Ping BE wg (${BE_WG_IP})"
  if ping -c 3 -W 2 "$BE_WG_IP"; then
    ok "ping ${BE_WG_IP}"
  else
    warn "ping failed — routing or AllowedIPs (expected 172.200.2.1/32)"
  fi
  note "9. Teardown"
  sudo wg-quick down "$CONF"
  ok "wg-quick down"
else
  note "7–9. Skipped tunnel (pass --apply or RA_UDP_APPLY=1 to test handshake)"
  echo "    sudo wg-quick up $CONF && ping -c3 $BE_WG_IP && sudo wg-quick down $CONF"
fi

note "UDP debug done"
