#!/usr/bin/env bash
# Prepare eth0/eth1 for fixture directional routing (not br0).
# Run with sudo before hat_fixture_bridge.sh on pos 3 / 4.
#
#   sudo ./prep_eth_for_ethergold.sh

set -euo pipefail

PORTS=(eth0 eth1)

if [[ "${EUID}" -ne 0 ]]; then
  echo "Run with sudo: sudo $0" >&2
  exit 1
fi

if pgrep -f 'pog422_fixture_bridge|broadcast_br_script' >/dev/null 2>&1; then
  echo "FATAL: stop bridge Python first (Ctrl+C on hat_fixture_bridge / broadcast script)" >&2
  exit 1
fi

if ip link show br0 >/dev/null 2>&1; then
  echo "Bringing br0 down (fixture uses eth0/eth1 directly)..."
  ip link set br0 down 2>/dev/null || true
fi

for p in "${PORTS[@]}"; do
  if [[ ! -d "/sys/class/net/${p}" ]]; then
    echo "WARN: ${p} not found — skip" >&2
    continue
  fi
  ip link set "${p}" nomaster 2>/dev/null || true
  ip link set "${p}" up
done

# Bridge runs as topbox (not root). AF_PACKET SOCK_RAW needs cap_net_raw on python3.
PY3="$(readlink -f "$(command -v python3)")"
if getcap "${PY3}" 2>/dev/null | grep -q 'cap_net_raw'; then
  echo "cap_net_raw already on ${PY3}"
else
  if ! command -v setcap >/dev/null 2>&1; then
    echo "WARN: setcap missing — install libcap2-bin, then re-run prep_eth" >&2
  else
    echo "Granting cap_net_raw to ${PY3} (required for eth0/eth1 raw sockets as ${SUDO_USER:-topbox})..."
    setcap cap_net_raw+ep "${PY3}"
    getcap "${PY3}" || true
  fi
fi

echo "Ready:"
for dev in br0 "${PORTS[@]}"; do
  ip -br link show "${dev}" 2>/dev/null || true
done
