#!/usr/bin/env bash
# report-session.sh — shim for forwarding CoovaChilli auth events to Weird Network.
#
# CoovaChilli itself doesn't POST to a third-party API on successful auth, so this
# script is the bridge. Wire it into one of:
#   - CoovaChilli's HS_UAM_SCRIPT (fires on successful authentication)
#   - cron:    * * * * * /opt/wn/report-session.sh ...
#   - hotplug: /etc/hotplug.d/net/99-weird-network
#
# Body shape matches POST /api/sessions/start schema in
# routes/captivePortalSessions.js (mac_address, provider_id, location_id,
# auth_method [+ optional router_id, ip_address]).
#
# Conventions match the MAC regex /^[0-9a-f]{2}([:][0-9a-f]{2}){5}$/i in
# routes/captivePortalSessions.js:29 and the auth_method enum
# (form_capture / social_gate / voucher).

set -euo pipefail

# ── Config ──────────────────────────────────────────────────────────────────
# Provider identity for this box — read from env first, fall back to /etc file.
PROVIDER_ID="${WEIRD_NETWORK_PROVIDER_ID:-}"
LOCATION_ID_DEFAULT="${WEIRD_NETWORK_LOCATION_ID:-}"
ROUTER_ID_DEFAULT="${WEIRD_NETWORK_ROUTER_ID:-}"
API_URL="${WEIRD_NETWORK_API_URL:-https://weird-network.io/api/sessions/start}"

if [[ -z "$PROVIDER_ID" && -f /etc/weird-network.conf ]]; then
  # shellcheck disable=SC1091
  source /etc/weird-network.conf || true
fi

# ── Arg parse ───────────────────────────────────────────────────────────────
MAC=""
IP=""
AUTH_METHOD=""
LOCATION_ID="$LOCATION_ID_DEFAULT"
ROUTER_ID="$ROUTER_ID_DEFAULT"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --mac)        MAC="$2"; shift 2 ;;
    --ip)         IP="$2"; shift 2 ;;
    --auth)       AUTH_METHOD="$2"; shift 2 ;;
    --location)   LOCATION_ID="$2"; shift 2 ;;
    --router)     ROUTER_ID="$2"; shift 2 ;;
    --provider)   PROVIDER_ID="$2"; shift 2 ;;
    --api-url)    API_URL="$2"; shift 2 ;;
    -h|--help)
      cat <<USAGE
Usage: $0 --mac AA:BB:CC:DD:EE:FF --auth form_capture [--ip 10.0.0.42] [--location 7] [--router 3] [--provider 42] [--api-url URL]

Env (or /etc/weird-network.conf):
  WEIRD_NETWORK_PROVIDER_ID  numeric provider id
  WEIRD_NETWORK_LOCATION_ID  numeric location id (optional, can be passed via --location)
  WEIRD_NETWORK_ROUTER_ID    numeric router id (optional)
  WEIRD_NETWORK_API_URL      override API endpoint (default https://weird-network.io/api/sessions/start)
USAGE
      exit 0
      ;;
    *) echo "report-session.sh: unknown arg: $1" >&2; exit 2 ;;
  esac
done

# ── Validate ─────────────────────────────────────────────────────────────────
if [[ -z "$MAC" || -z "$AUTH_METHOD" || -z "$PROVIDER_ID" || -z "$LOCATION_ID" ]]; then
  echo "report-session.sh: missing required --mac / --auth / provider_id / location_id" >&2
  exit 2
fi

if [[ ! "$MAC" =~ ^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$ ]]; then
  echo "report-session.sh: invalid MAC format: '$MAC' (expected AA:BB:CC:DD:EE:FF)" >&2
  exit 3
fi

case "$AUTH_METHOD" in
  form_capture|social_gate|voucher) ;;
  *) echo "report-session.sh: invalid --auth '$AUTH_METHOD' (expected form_capture|social_gate|voucher)" >&2; exit 3 ;;
esac

# ── Build JSON body ──────────────────────────────────────────────────────────
# jq may not exist on OpenWrt; assemble JSON with printf-side escaping to stay
# portable. printf %q is bash-only; we emit JSON manually with the only
# variable that could contain quotes (IP, which is dotted-decimal — none).
ip_field=""
if [[ -n "$IP" ]]; then ip_field=",\"ip_address\":\"$IP\""; fi
router_field=""
if [[ -n "$ROUTER_ID" ]]; then router_field=",\"router_id\":$ROUTER_ID"; fi

payload=$(printf '{"mac_address":"%s","provider_id":%s,"location_id":%s,"auth_method":"%s"%s%s}' \
  "$MAC" "$PROVIDER_ID" "$LOCATION_ID" "$AUTH_METHOD" "$ip_field" "$router_field")

# ── POST ─────────────────────────────────────────────────────────────────────
http_code=$(curl -sS -o /tmp/wn-report.body -w '%{http_code}' \
  -X POST \
  -H 'Content-Type: application/json' \
  --data "$payload" \
  "$API_URL" || echo "000")

if [[ "$http_code" =~ ^2 ]]; then
  echo "[$(date -Iseconds)] PASS mac=$MAC auth=$AUTH_METHOD loc=$LOCATION_ID http=$http_code"
  exit 0
else
  echo "[$(date -Iseconds)] FAIL mac=$MAC auth=$AUTH_METHOD loc=$LOCATION_ID http=$http_code" >&2
  cat /tmp/wn-report.body >&2 || true
  exit 1
fi
