#!/usr/bin/env bash
# Blaze switch — COMPATIBILITY WRAPPER over openfut-switch.sh.
#
#   blaze-switch.sh status
#   blaze-switch.sh on  <LAN_IP> <RUST_PORT>   Blaze -> Rust sidecar
#   blaze-switch.sh off                        Blaze -> Python (rollback)
#
# The CLI and output are unchanged from the version used for gates 5–10, so the
# validated Blaze runbook and `sidecar.sh`'s cross-check keep working exactly as
# before. All iptables logic now lives in `openfut-switch.sh`: one
# implementation, because two scripts editing the same table diverge and then
# disagree about what is installed.
#
# The only Blaze-specific knowledge left here is the intercepted port, 42130,
# which the generic tool never assumes.
set -uo pipefail

HERE="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"
GENERIC="$HERE/openfut-switch.sh"
BLAZE_PORT=42130
NAME=blaze
# Tag used before the switch was generalised. Rules installed by the gate 5-10
# tooling still carry it, so they must remain removable — a rename that orphans
# live NAT rules is worse than no rename at all.
LEGACY_TAG=openfut-blaze-switch

[[ -x "$GENERIC" ]] || { echo "blaze-switch: missing $GENERIC" >&2; exit 2; }

case "${1:-}" in
  status)
    # Translate the generic report into the wording the Blaze runbook and
    # sidecar.sh already match on ("redirected to the RUST" / "served by
    # PYTHON"). Kept verbatim so the proven tooling does not change.
    out="$("$GENERIC" status --name "$NAME" --legacy-tag "$LEGACY_TAG" --intercept-port "$BLAZE_PORT" 2>&1)"
    rc=$?
    if grep -q '^INACTIVE' <<<"$out"; then
      echo "Blaze is served by PYTHON (no switch rules)"
    else
      echo "Blaze is redirected to the RUST sidecar:"
      grep -E '^\s+(blaze|openfut-switch)' <<<"$out" | sed 's/^/  /'
      grep -E '^\s+!!|\?\?' <<<"$out" >&2 || true
    fi
    exit $rc
    ;;
  on)
    shift
    ip="${1:-}"; port="${2:-}"
    [[ -n "$ip" && -n "$port" ]] || {
      echo "usage: blaze-switch.sh on <LAN_IP> <RUST_PORT>" >&2; exit 2; }
    "$GENERIC" on --name "$NAME" --legacy-tag "$LEGACY_TAG" --server-ip "$ip" \
        --intercept-port "$BLAZE_PORT" --target-port "$port" >/dev/null || exit 1
    echo "Blaze -> RUST: $ip:$BLAZE_PORT now lands on local port $port"
    echo "  127.0.0.1:$BLAZE_PORT still reaches PYTHON (unmatched by design)"
    echo "  roll back with: $0 off"
    echo
    echo "  NOTE: while this is on, the sidecar MUST stay up. Stopping it without"
    echo "  switching off leaves Blaze pointing at a dead port."
    ;;
  off)
    out="$("$GENERIC" off --name "$NAME" --legacy-tag "$LEGACY_TAG" --intercept-port "$BLAZE_PORT" 2>&1)"
    rc=$?
    if [[ $rc -ne 0 ]]; then
      echo "$out" >&2
      exit $rc
    fi
    n="$(sed -nE 's/.*removed ([0-9]+) rule.*/\1/p' <<<"$out")"
    echo "Blaze -> PYTHON: removed ${n:-0} rule(s), verified none remain"
    ;;
  *)
    sed -n '2,8p' "$0" | sed 's/^# \?//'
    exit 2
    ;;
esac
