#!/usr/bin/env bash
# Stop stale bridge/uartd/supervisor workers before a clean foreground run.
#
# Usage:
#   cd ~/EtherGold/sync
#   bash stop_fixture_gremlins.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

set -euo pipefail

echo "=== stop_fixture_gremlins ==="

# Office pos5 / field: stop prod systemd bridge so manual jun11-good does not fight ethergold.service.
for unit in ethergold.service fixture-prod.service; do
  if command -v systemctl >/dev/null 2>&1 && systemctl list-unit-files "${unit}" >/dev/null 2>&1; then
    if systemctl is-active --quiet "${unit}" 2>/dev/null; then
      echo "systemctl stop ${unit}"
      sudo systemctl stop "${unit}" 2>/dev/null || true
    fi
  fi
done

for pattern in pog422_fixture_bridge fixture_link_watch fixture_supervisor pog422_fixture_listen; do
  if pgrep -f "${pattern}" >/dev/null 2>&1; then
    echo "pkill -TERM -f ${pattern}"
    pkill -TERM -f "${pattern}" 2>/dev/null || true
  fi
done
sleep 0.5
for pattern in pog422_fixture_bridge fixture_link_watch fixture_supervisor pog422_fixture_listen pog422_uartd; do
  if pgrep -f "${pattern}" >/dev/null 2>&1; then
    echo "pkill -KILL -f ${pattern}"
    pkill -KILL -f "${pattern}" 2>/dev/null || true
  fi
done

rm -f /tmp/pog422_uart_*.sock 2>/dev/null || true
for pos in 1 2 3 4 5; do
  rm -f "/tmp/pog422_uart_${pos}.sock" 2>/dev/null || true
done

for pf in \
  "/home/topbox/EtherGold/4-Board Test Fixture/fixture-timing/.bridge.pid" \
  "/home/topbox/EtherGold/bridge/.bridge.pid"; do
  [[ -f "${pf}" ]] && rm -f "${pf}" && echo "removed ${pf}"
done

echo "done — pgrep check:"
pgrep -af 'pog422_uartd|pog422_fixture_bridge|fixture_link_watch' || echo "  (none)"
