#!/usr/bin/env bash
# Apply CHANNEL=machine + uartd C-spine (UARTD+INJECT) on a chain hop, restart fixture-prod.
# EG 2.2 hard-requires POG422_UARTD_INJECT=1 (Python MARK/SPACE removed).
set -euo pipefail

ENV=/etc/fixture/fixture-pos.env
POS=$(grep -E '^FIXTURE_POS=' "$ENV" 2>/dev/null | cut -d= -f2 || echo 1)
MODE=$(grep -E '^FIXTURE_MODE=' "$ENV" 2>/dev/null | cut -d= -f2 || echo bridge)
LED=$(grep -E '^FIXTURE_STATUS_LED=' "$ENV" 2>/dev/null | cut -d= -f2 || echo 1)

{
  echo "FIXTURE_POS=${POS}"
  echo "FIXTURE_MODE=${MODE}"
  echo "CHANNEL=machine"
  echo "POG422_UARTD=1"
  echo "POG422_UARTD_INJECT=1"
  echo "FIXTURE_STATUS_LED=${LED}"
} | sudo tee "$ENV" >/dev/null

# Prefer fixture-prod; stop legacy ethergold if present (dual supervisors fight).
if systemctl list-unit-files ethergold.service 2>/dev/null | grep -q ethergold.service; then
  sudo systemctl stop ethergold 2>/dev/null || true
  sudo systemctl disable ethergold 2>/dev/null || true
fi

# CRLF in edge.env aborts run_bridge_prod (source) before bridge starts.
# --follow-symlinks: /etc/fixture/edge.env may be a symlink to the canonical
# /etc/ethergold/edge.env; plain sed -i would replace the link with a copy.
for ee in /etc/ethergold/edge.env /etc/fixture/edge.env; do
  if [ -f "$ee" ]; then
    sudo sed -i --follow-symlinks 's/\r$//' "$ee"
  fi
done

pkill -TERM -f pog422_uartd 2>/dev/null || true
sleep 1
pkill -KILL -f pog422_uartd 2>/dev/null || true

cd "${HOME}/EtherGold/prod"
make -C inject-shim pog422_uartd
test -x inject-shim/pog422_uartd

sudo systemctl restart fixture-prod
sleep 5

echo "hostname=$(hostname -s)"
echo "ENV:"
cat "$ENV"
echo "fixture-prod=$(systemctl is-active fixture-prod)"
echo "ethergold=$(systemctl is-active ethergold 2>/dev/null || echo inactive)"
echo "uartd=$(pgrep -a pog422_uartd | head -1 || echo none)"
echo "bridge=$(pgrep -af 'pog422_fixture_bridge' | head -1 || echo none)"
echo "--- supervisor ---"
tail -20 "${HOME}/EtherGold/logs/supervisor.log" 2>/dev/null || true
