#!/usr/bin/env bash
# Install NM eth unmanaged drop-in, reload NM, restart fixture-prod.
# Used by apply_nm_eth_unmanaged.ps1 (SCP + remote bash).
set -euo pipefail

SCRIPT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/install_nm_eth_unmanaged.sh"
if [[ ! -f "${SCRIPT}" ]]; then
  # When SCP lands only this wrapper in /tmp, expect companion next to it.
  SCRIPT="/tmp/install_nm_eth_unmanaged.sh"
fi
if [[ ! -f "${SCRIPT}" ]]; then
  echo "FATAL: missing install_nm_eth_unmanaged.sh" >&2
  exit 1
fi

sed -i 's/\r$//' "${SCRIPT}" 2>/dev/null || true
sudo bash "${SCRIPT}"

# Prefer fixture-prod; leave ethergold alone here (apply_chain_machine_uartd owns that).
if systemctl list-unit-files fixture-prod.service 2>/dev/null | grep -q fixture-prod.service; then
  sudo systemctl restart fixture-prod
  sleep 4
fi

echo "hostname=$(hostname -s)"
echo "fixture-prod=$(systemctl is-active fixture-prod 2>/dev/null || echo n/a)"
echo "bridge=$(pgrep -c -f 'pog422_fixture_bridge' 2>/dev/null || echo 0)"
if command -v nmcli >/dev/null 2>&1; then
  for p in eth0 eth1; do
    if [[ -d "/sys/class/net/${p}" ]]; then
      m=$(nmcli -g GENERAL.NM-MANAGED device show "${p}" 2>/dev/null || echo "?")
      echo "NM-MANAGED ${p}=${m}"
    fi
  done
fi
[[ -f /etc/NetworkManager/conf.d/10-ethergold-unmanaged.conf ]] && echo "conf10=ok" || echo "conf10=MISSING"
[[ -f /etc/NetworkManager/conf.d/20-ethergold-edge.conf ]] && echo "conf20=present" || echo "conf20=none"
