#!/usr/bin/env bash
# Remove production systemd service and stop all prod workers.
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"

bash "${SCRIPT_DIR}/disable_prod.sh" || true

for unit in "${ETHERGOLD_UNIT}" "${ETHERGOLD_UNIT_LEGACY}" \
            "${ETHERGOLD_COLLECTOR_UNIT}" "${ETHERGOLD_COLLECTOR_UNIT_LEGACY}"; do
  if systemctl list-unit-files "${unit}" >/dev/null 2>&1; then
    sudo systemctl stop "${unit}" 2>/dev/null || true
    sudo systemctl disable "${unit}" 2>/dev/null || true
    sudo rm -f "/etc/systemd/system/${unit}"
    echo "Removed ${unit}"
  fi
done
sudo systemctl daemon-reload

for pattern in ethergold_supervisor fixture_supervisor fixture_link_watch \
               pog422_fixture_bridge pog422_bridge ethergold_listen_supervisor; do
  sudo pkill -TERM -f "${pattern}" 2>/dev/null || true
done

echo "EtherGold production uninstalled. dev stack unchanged."
