#!/usr/bin/env bash
# Return all four positions to jun11-good debug capture (disable prod supervisor).
#
# Usage from PC after end-session:
#   cd sync && ./switch_all_debug.sh
# Or per-host via orchestrate after deploy.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=ethergold_paths.sh
source "${SCRIPT_DIR}/ethergold_paths.sh"
export FIXTURE_MODE=debug
# shellcheck source=source_fixture_env.sh
source "${SCRIPT_DIR}/source_fixture_env.sh"
# shellcheck source=resolve_bench_timing.sh
source "${SCRIPT_DIR}/resolve_bench_timing.sh"

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

TIMING="$(resolve_bench_timing_root)"
POS="${FIXTURE_POS:-}"

stop_all() {
  for pattern in fixture_supervisor fixture_link_watch pog422_fixture_bridge pog422_fixture_listen; do
    pkill -TERM -f "${pattern}" 2>/dev/null || true
  done
  sleep 1
  for pattern in fixture_supervisor fixture_link_watch pog422_fixture_bridge pog422_fixture_listen; do
    pkill -KILL -f "${pattern}" 2>/dev/null || true
  done
  rm -f "${TIMING}/.bridge.pid"
}

start_debug() {
  export FIXTURE_MODE=debug
  export FIXTURE_PROD=0
  export POG422_UARTD=0
  export POG422_UARTD_CAPTURE=0
  export POG422_UARTD_INJECT=0
  pkill -TERM -f pog422_uartd 2>/dev/null || true
  sleep 0.5
  pkill -KILL -f pog422_uartd 2>/dev/null || true
  export FIXTURE_LAB_KENO_JPOT_SYNTH=0
  export CHANNEL="${CHANNEL:-both}"
  export CLEAR_CAPTURE="${CLEAR_CAPTURE:-1}"
  echo "=== start jun11-good debug bridge pos=${FIXTURE_POS} CHANNEL=${CHANNEL} ==="
  echo "  capture -> ${TIMING}/data/  logs -> ${TIMING}/logs/"
  cd "${TIMING}"
  FIXTURE_POS="${FIXTURE_POS}" bash start_bridge_background.sh
}

if [[ -n "${POS}" ]]; then
  FIXTURE_POS="${POS}" bash "${SCRIPT_DIR}/disable_bench_prod.sh"
  bash "${SCRIPT_DIR}/enable_lab_keno_jpot_env.sh" --off 2>/dev/null || true
  bash "${SCRIPT_DIR}/enable_lab_poker_royal_env.sh" --off 2>/dev/null || true
  bash "${SCRIPT_DIR}/enable_lab_spinjack_flushjack_env.sh" --off 2>/dev/null || true
  bash "${SCRIPT_DIR}/enable_lab_touch6_jpot_env.sh" --off 2>/dev/null || true
  stop_all
  start_debug
  exit 0
fi

echo "FATAL: FIXTURE_POS=1..4 required (run from orchestrate per Pi)" >&2
exit 1
