#!/bin/sh
# wg-mgmt-fix.sh — apply ONE mgmt-tunnel robustness fix at a time, then bounce wgclient1.
# Run ON THE ROUTER over LAN:  ssh root@192.168.8.1 (pw kitPLANE1!!)
#   sh wg-mgmt-fix.sh keepalive   # set persistent_keepalive=25  (TRY FIRST)
#   sh wg-mgmt-fix.sh mtu         # set wgclient1 mtu=1280       (fixes PMTU black-holes / SSH data)
#   sh wg-mgmt-fix.sh rpfilter    # persist loose rp_filter (=2) + hotplug re-assert
#   sh wg-mgmt-fix.sh all         # keepalive + mtu + rpfilter
# MUTATING but reversible (each is a uci change). Bounces the tunnel ~5s; touches nothing else.
# After each: re-test  ping -c3 -W2 -I 10.88.0.2 10.88.0.1  (expect replies).
# Rationale + goal (mgmt over EITHER WAN): docs/handoff/2026-07-01-wg-mgmt-incident-and-resume.md
set -e
IFACE=wgclient1

bounce() { echo ">> uci commit network; ifup $IFACE"; uci commit network; ifup "$IFACE"; sleep 5; }

do_keepalive() {
  echo "== persistent_keepalive=25 on $IFACE (hold NAT mapping open on whichever WAN) =="
  uci set network.$IFACE.persistent_keepalive='25'
  bounce
}

do_mtu() {
  echo "== mtu=1280 on $IFACE (safe under cellular + ATT-fiber/PPPoE path MTUs) =="
  uci set network.$IFACE.mtu='1280'
  bounce
}

do_rpfilter() {
  echo "== persist loose rp_filter (=2) so multi-WAN policy-routed mgmt isn't dropped =="
  grep -q 'busrouter: loose reverse-path' /etc/sysctl.conf 2>/dev/null || cat >> /etc/sysctl.conf <<'EOF'
# busrouter: loose reverse-path filtering for multi-WAN WG mgmt failover
net.ipv4.conf.all.rp_filter=2
net.ipv4.conf.default.rp_filter=2
EOF
  # apply now
  sysctl -w net.ipv4.conf.all.rp_filter=2 >/dev/null
  for f in /proc/sys/net/ipv4/conf/*/rp_filter; do echo 2 > "$f"; done
  # re-assert on WAN flaps (GL DHCP hooks may re-tighten per-iface)
  mkdir -p /etc/hotplug.d/iface
  cat > /etc/hotplug.d/iface/99-busrouter-rpfilter <<'EOF'
#!/bin/sh
[ "$ACTION" = ifup ] || exit 0
for f in /proc/sys/net/ipv4/conf/*/rp_filter; do echo 2 > "$f" 2>/dev/null; done
EOF
  chmod +x /etc/hotplug.d/iface/99-busrouter-rpfilter
  echo "   rp_filter now: all=$(cat /proc/sys/net/ipv4/conf/all/rp_filter)"
}

case "$1" in
  keepalive) do_keepalive ;;
  mtu)       do_mtu ;;
  rpfilter)  do_rpfilter ;;
  all)       do_keepalive; do_mtu; do_rpfilter ;;
  *) echo "usage: $0 {keepalive|mtu|rpfilter|all}"; exit 2 ;;
esac

echo
echo ">> Now verify:  ping -c3 -W2 -I 10.88.0.2 10.88.0.1   (replies = mgmt tunnel healthy)"
