#!/usr/bin/env bash
# Emit one identity + copper-peer line for map_chain_topology.ps1.
# Fields (pipe-separated):
#   octet|host|eth0_mac|eth1_mac|wlan_mac|wlan_ip|eth0_carrier|eth1_carrier|eth0_peers|eth1_peers
# QUICK=1 skips tcpdump peer capture (inventory only).
set -euo pipefail

h=$(hostname -s)
o="${h#topbox}"
# Office Pi is often hostname "topbox" (no seat digit) — derive from wlan IP.
if [[ -z "${o}" || "${o}" == "${h}" || ! "${o}" =~ ^[0-9]+$ ]]; then
  o=$(ip -4 -o addr show dev wlan0 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | awk -F. '{print $4}')
fi
if [[ -z "${o}" ]]; then
  o="0"
fi

_mac() {
  local ifc=$1
  if [[ -r "/sys/class/net/${ifc}/address" ]]; then
    tr 'A-Z' 'a-z' <"/sys/class/net/${ifc}/address"
  else
    echo ""
  fi
}

_carrier() {
  local ifc=$1
  if [[ -r "/sys/class/net/${ifc}/carrier" ]]; then
    cat "/sys/class/net/${ifc}/carrier" 2>/dev/null || echo "?"
  else
    echo "-"
  fi
}

_wlan_ip() {
  local ifc=${1:-wlan0}
  ip -4 -o addr show dev "$ifc" 2>/dev/null \
    | awk '{print $4}' | cut -d/ -f1 | head -n1
}

e0=$(_mac eth0)
e1=$(_mac eth1)
wmac=$(_mac wlan0)
wip=$(_wlan_ip wlan0)
c0=$(_carrier eth0)
c1=$(_carrier eth1)

_peers() {
  local ifc=$1 tmp
  if [[ "${QUICK:-0}" == "1" ]]; then
    echo ""
    return 0
  fi
  if ! command -v tcpdump >/dev/null 2>&1; then
    echo ""
    return 0
  fi
  tmp=$(mktemp)
  # Broadcast sources on this copper leg (needs live STOM/gameplay on chain).
  sudo timeout 8 tcpdump -l -i "$ifc" -e -nn -c 40 \
    "ether dst ff:ff:ff:ff:ff:ff and not ether src ${e0} and not ether src ${e1}" \
    >"$tmp" 2>/dev/null || true
  awk '/>/ { print tolower($2) }' "$tmp" | sort -u | paste -sd, - 2>/dev/null || true
  rm -f "$tmp"
}

# Also merge ip-neigh L2 entries when present (works without broadcast storm).
_neigh_macs() {
  local ifc=$1
  ip neigh show dev "$ifc" 2>/dev/null \
    | awk '/lladdr/ { print tolower($5) }' | sort -u | paste -sd, - 2>/dev/null || true
}

_merge_macs() {
  local a=$1 b=$2
  printf '%s\n%s\n' "${a//,/ }" "${b//,/ }" \
    | tr ' ' '\n' | awk 'NF && $0 ~ /:/' | sort -u | paste -sd, -
}

if [[ "${QUICK:-0}" == "1" ]]; then
  p0=$(_neigh_macs eth0)
  p1=$(_neigh_macs eth1)
else
  p0=$(_merge_macs "$(_peers eth0)" "$(_neigh_macs eth0)")
  p1=$(_merge_macs "$(_peers eth1)" "$(_neigh_macs eth1)")
fi

echo "${o}|${h}|${e0}|${e1}|${wmac}|${wip}|${c0}|${c1}|${p0}|${p1}"
