#!/bin/bash
# NetBird iptables rules - add only, no flush to preserve Docker rules

# DNAT rules for incoming traffic (only from vmbr0/external)
iptables -t nat -C PREROUTING -i vmbr0 -p tcp --dport 80 -j DNAT --to-destination 192.168.222.111:80 2>/dev/null || \
  iptables -t nat -A PREROUTING -i vmbr0 -p tcp --dport 80 -j DNAT --to-destination 192.168.222.111:80

iptables -t nat -C PREROUTING -i vmbr0 -p tcp --dport 443 -j DNAT --to-destination 192.168.222.111:443 2>/dev/null || \
  iptables -t nat -A PREROUTING -i vmbr0 -p tcp --dport 443 -j DNAT --to-destination 192.168.222.111:443

iptables -t nat -C PREROUTING -i vmbr0 -p udp --dport 3478 -j DNAT --to-destination 192.168.222.111:3478 2>/dev/null || \
  iptables -t nat -A PREROUTING -i vmbr0 -p udp --dport 3478 -j DNAT --to-destination 192.168.222.111:3478

# FORWARD rules for container traffic
iptables -C FORWARD -p tcp -d 192.168.222.111 --dport 80 -j ACCEPT 2>/dev/null || \
  iptables -A FORWARD -p tcp -d 192.168.222.111 --dport 80 -j ACCEPT

iptables -C FORWARD -p tcp -d 192.168.222.111 --dport 443 -j ACCEPT 2>/dev/null || \
  iptables -A FORWARD -p tcp -d 192.168.222.111 --dport 443 -j ACCEPT

iptables -C FORWARD -p udp -d 192.168.222.111 --dport 3478 -j ACCEPT 2>/dev/null || \
  iptables -A FORWARD -p udp -d 192.168.222.111 --dport 3478 -j ACCEPT

# Ensure MASQUERADE exists for container outbound traffic
iptables -t nat -C POSTROUTING -s 192.168.222.0/24 -o vmbr0 -j MASQUERADE 2>/dev/null || \
  iptables -t nat -A POSTROUTING -s 192.168.222.0/24 -o vmbr0 -j MASQUERADE

echo ok
