#!/usr/bin/env bash
# Create disable flag — supervisor idles, bridge stays stopped.
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

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

DISABLE_FILE="${ETHERGOLD_DISABLE_FILE}"
POS="${FIXTURE_POS:-}"

sudo mkdir -p "$(dirname "${DISABLE_FILE}")"
sudo touch "${DISABLE_FILE}"
# Mirror legacy path so old supervisors still see disable
sudo mkdir -p "${ETHERGOLD_VAR_LEGACY}"
sudo touch "${ETHERGOLD_VAR_LEGACY}/disabled" 2>/dev/null || true
echo "EtherGold production DISABLED (${DISABLE_FILE})"

for unit in "${ETHERGOLD_UNIT}" "${ETHERGOLD_UNIT_LEGACY}"; do
  if systemctl list-unit-files "${unit}" >/dev/null 2>&1; then
    sudo systemctl stop "${unit}" 2>/dev/null || true
    if [[ "${FIXTURE_BENCH:-0}" == "1" ]] || [[ "${BENCH_DISABLE_PROD:-0}" == "1" ]]; then
      sudo systemctl disable "${unit}" 2>/dev/null || true
      echo "${unit} disabled at boot (bench)"
    fi
  fi
done

if [[ -n "${POS}" ]]; then
  for pattern in \
    "ethergold_supervisor.py --fixture-pos ${POS}" \
    "fixture_supervisor.py --fixture-pos ${POS}" \
    "fixture_link_watch.py --fixture-pos ${POS}" \
    "pog422_fixture_bridge.py --fixture-pos ${POS}" \
    "pog422_bridge.py --fixture-pos ${POS}"; do
    pkill -TERM -f "${pattern}" 2>/dev/null || true
  done
  sleep 1
  for pattern in \
    "ethergold_supervisor.py --fixture-pos ${POS}" \
    "fixture_supervisor.py --fixture-pos ${POS}" \
    "fixture_link_watch.py --fixture-pos ${POS}" \
    "pog422_fixture_bridge.py --fixture-pos ${POS}" \
    "pog422_bridge.py --fixture-pos ${POS}"; do
    pkill -KILL -f "${pattern}" 2>/dev/null || true
  done
fi

echo "Stop complete. Re-enable: bash $(dirname "$0")/enable_prod.sh"
