#!/usr/bin/env bash
# Release a stuck POG422 bus on this Pi: stop software, re-apply RS485 auto, read SLV-IN.
#
# Run on ALL fixture Pis (1–4) when MST_HS / SLV_HS are stuck active before restarting bridges.
#
# Usage:
#   bash bus_recovery.sh
#   FIXTURE_POS=3 bash bus_recovery.sh

set -euo pipefail

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

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "${ROOT}"

FIXTURE_POS="${FIXTURE_POS:-?}"
echo "=== POG422 bus recovery (FIXTURE_POS=${FIXTURE_POS}) ==="

echo "--- Stop fixture processes on this Pi ---"
pkill -f pog422_uartd 2>/dev/null || true
pkill -f pog422_fixture_bridge 2>/dev/null || true
pkill -f pog422_fixture_listen 2>/dev/null || true
sleep 0.5
if command -v fuser >/dev/null 2>&1; then
  for dev in /dev/ttyXRUSB*; do
    [[ -e "$dev" ]] || continue
    sudo fuser -k "$dev" 2>/dev/null || true
  done
fi
sleep 0.5

if [[ -x "${ROOT}/xr-usb-serial-pog422/remove_gpio7low.sh" ]]; then
  if systemctl list-unit-files gpio7low.service 2>/dev/null | grep -q gpio7low; then
    echo "--- Removing gpio7low (manual GPIO7 fights RS485 auto) ---"
    bash "${ROOT}/xr-usb-serial-pog422/remove_gpio7low.sh" || true
  fi
fi

if [[ ! -e /dev/ttyXRUSB1 ]]; then
  echo "FATAL: /dev/ttyXRUSB1 missing — check hat USB / driver (install_pi.sh)" >&2
  exit 1
fi

echo "--- Hat state (MST+SLV HS + GPIO_MODE on both UART blocks) ---"
if ! python3 "${ROOT}/read_hat_state.py"; then
  rc=$?
  echo
  echo "SLV-HS still active or GPIO_MODE wrong on this Pi (exit ${rc})." >&2
  echo "Try on this Pi:" >&2
  echo "  1. Unplug hat USB 5 seconds, replug" >&2
  echo "  2. sudo dmesg -T | grep -i POG422   # want RS485 auto probe line" >&2
  echo "  3. Re-run: bash bus_recovery.sh" >&2
  echo
  echo "If STILL active with no software running, the lock is upstream:" >&2
  echo "  - Stop bridges on ALL positions (3 and 4 minimum)" >&2
  echo "  - Power-cycle the T340+ / machine segment" >&2
  echo "  - Check copper trunk (pos 1/2 listen should be stopped too)" >&2
  exit "${rc}"
fi

echo
echo "This Pi looks idle. Repeat bus_recovery.sh on every other fixture Pi before run_bridge."
