#!/bin/bash
# FE (f0xx-monstro): DNAT public UDP → BE wg0. Matches existing rules to 10.7.16.128 (8088, etc.).
# Invoked from xen_firewall.sh start/stop; also: wireguard_fe_dnat.sh [start|stop]
set -euo pipefail

BE_IP="${BE_IP:-10.7.16.128}"
WG_PORT="${WG_PORT:-45340}"

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

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

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

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

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