#!/bin/bash
# Raspberry Pi router (f0xx.org): WAN UDP 45340 → FE (10.7.0.10).
# Invoked at boot or from iodine_warmup_helper; also: router_wireguard_dnat.sh [start|stop]
set -euo pipefail

FE_IP="${FE_IP:-10.7.0.10}"
WG_PORT="${WG_PORT:-45340}"
WAN_IF="${WAN_IF:-eth0}"

function start() {
  if iptables -t nat -C PREROUTING -i "$WAN_IF" -p udp --dport "$WG_PORT" -j DNAT --to-destination "${FE_IP}:${WG_PORT}" 2>/dev/null; then
    echo "Router DNAT already present for udp/${WG_PORT}"
  else
    iptables -t nat -A PREROUTING -i "$WAN_IF" -p udp --dport "$WG_PORT" -j DNAT --to-destination "${FE_IP}:${WG_PORT}"
    echo "Added router PREROUTING udp/${WG_PORT} -> ${FE_IP}:${WG_PORT}"
  fi

  if iptables -C FORWARD -p udp -d "${FE_IP}" --dport "$WG_PORT" -j ACCEPT 2>/dev/null; then
    echo "Router FORWARD rule already present"
  else
    iptables -A FORWARD -p udp -d "${FE_IP}" --dport "$WG_PORT" -j ACCEPT
    echo "Added router FORWARD udp -> ${FE_IP}:${WG_PORT}"
  fi
}

function stop() {
  if iptables -t nat -C PREROUTING -i "$WAN_IF" -p udp --dport "$WG_PORT" -j DNAT --to-destination "${FE_IP}:${WG_PORT}" 2>/dev/null; then
    iptables -t nat -D PREROUTING -i "$WAN_IF" -p udp --dport "$WG_PORT" -j DNAT --to-destination "${FE_IP}:${WG_PORT}"
    echo "Removed router PREROUTING DNAT udp/${WG_PORT}"
  else
    echo "Router DNAT rule not present for udp/${WG_PORT}"
  fi

  if iptables -C FORWARD -p udp -d "${FE_IP}" --dport "$WG_PORT" -j ACCEPT 2>/dev/null; then
    iptables -D FORWARD -p udp -d "${FE_IP}" --dport "$WG_PORT" -j ACCEPT
    echo "Removed router FORWARD udp -> ${FE_IP}:${WG_PORT}"
  else
    echo "Router FORWARD rule not present"
  fi
}

cmd=$1
cmd=${cmd:-start}
[ "$cmd" = "start" ] && start || stop
