#!/usr/bin/env bash
# Persist HS timing diagnostics in ~/EtherGold/fixture-bridge.env (EG tip 3.0.1.9+).
#
# Evidence-only trace (kernel GPIO/RX ring + uartd timeline). No wire-path change,
# but it does write a JSONL file every flush — keep it scoped to the seat under study.
#
# Usage (on the Pi):
#   cd ~/EtherGold/sync
#   bash enable_hs_timing_env.sh            # pos5 (or its witness 51) only
#   bash enable_hs_timing_env.sh --off      # clear timing keys
#   bash enable_hs_timing_env.sh --force    # allow on a seat other than 5/51
#   bash enable_hs_timing_env.sh --path /home/topbox/EtherGold/dev/data/hs_timing.jsonl
#
# Default path is left unset so uartd lands the trace in ${OUTPUT_DIR}/hs_timing.jsonl
# (same folder as events.jsonl), which means sync_to_dropbox.sh picks it up.

if grep -q $'\r' "${BASH_SOURCE[0]}" 2>/dev/null; then
  sed -i 's/\r$//' "${BASH_SOURCE[0]}"
  exec bash "${BASH_SOURCE[0]}" "$@"
fi

set -euo pipefail

SYNC="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=ethergold_paths.sh
source "${SYNC}/ethergold_paths.sh"

DEST="${ETHERGOLD_ROOT}/fixture-bridge.env"
OFF=0
FORCE=0
TRACE_PATH=""

while (($#)); do
  case "$1" in
    --off) OFF=1 ;;
    --force) FORCE=1 ;;
    --path)
      shift
      TRACE_PATH="${1:-}"
      [[ -n "${TRACE_PATH}" ]] || { echo "FATAL: --path needs a value" >&2; exit 1; }
      ;;
    -h|--help)
      sed -n '2,15p' "${BASH_SOURCE[0]}"
      exit 0
      ;;
    *)
      echo "FATAL: unknown arg '$1' (see --help)" >&2
      exit 1
      ;;
  esac
  shift
done

if [[ ! -f "${DEST}" ]]; then
  bash "${SYNC}/install_fixture_bridge_env.sh" --ensure
fi

_seat() {
  local pos short
  pos="$(grep -E '^FIXTURE_POS=' "${DEST}" 2>/dev/null | tail -1 | cut -d= -f2 | tr -d '[:space:]')"
  if [[ -z "${pos}" ]]; then
    short="$(hostname -s 2>/dev/null || hostname)"
    short="${short%%.*}"
    if [[ "${short}" =~ ^topbox([1-5])(w|1)$ ]]; then
      pos=$((BASH_REMATCH[1] * 10 + 1))
    elif [[ "${short}" =~ ^topbox([1-5])$ ]]; then
      pos="${BASH_REMATCH[1]}"
    fi
  fi
  echo "${pos}"
}

SEAT="$(_seat)"

# Drop any prior timing block/keys so repeat runs stay idempotent. Never replace the
# env file with an empty one if grep misbehaves.
grep -v -E '^(POG422_TIMING_TRACE|POG422_TIMING_TRACE_PATH)=|^# EG HS timing diagnostics' \
  "${DEST}" > "${DEST}.tmp" || true
if [[ -s "${DEST}.tmp" ]]; then
  mv -f "${DEST}.tmp" "${DEST}"
else
  rm -f "${DEST}.tmp"
fi

if [[ "${OFF}" == "1" ]]; then
  echo "Cleared POG422_TIMING_TRACE* from ${DEST} (seat ${SEAT:-unknown})"
  echo "Restart the bridge/listen launcher for it to take effect."
  exit 0
fi

if [[ "${FORCE}" != "1" ]] && [[ "${SEAT}" != "5" && "${SEAT}" != "51" ]]; then
  echo "FATAL: HS timing trace is scoped to pos5 (seat 5) and its witness (seat 51)." >&2
  echo "  This Pi reports FIXTURE_POS=${SEAT:-unknown} in ${DEST}." >&2
  echo "  Use --force only if you intend to trace this seat too." >&2
  exit 1
fi

{
  echo "# EG HS timing diagnostics — enable_hs_timing_env.sh (seat ${SEAT})"
  echo "POG422_TIMING_TRACE=1"
  if [[ -n "${TRACE_PATH}" ]]; then
    echo "POG422_TIMING_TRACE_PATH=${TRACE_PATH}"
  fi
} >> "${DEST}"

echo "HS timing trace enabled in ${DEST} (seat ${SEAT}):"
grep -E '^POG422_TIMING_TRACE' "${DEST}"
if [[ -z "${TRACE_PATH}" ]]; then
  echo "Trace path: \${OUTPUT_DIR}/hs_timing.jsonl (default — beside events.jsonl)"
fi
echo "Restart the bridge/listen launcher, then analyze with:"
echo "  python3 ~/EtherGold/dev/hs_timing_analyze.py <path-to>/hs_timing.jsonl"
