#!/usr/bin/env nft -f

table ip filter {
	define FRIENDS = { {{ '\"' + ( lanInterfaces | join('\", \"') ) + '\"' }} , "tailscale0" }
	define SUS = { {{ limitedLan | join(", ") }} }
	define LAN = { $FRIENDS, $SUS }

	counter tcp_dns {}
	counter udp_dns {}
	counter catchall {}

	chain output {
		type filter hook output priority 100; policy accept;
	}

	chain input {
		type filter hook input priority 0; policy drop;

		iifname lo accept

		# Router needs to yield up DNS and DHCP for itself, in my case
		iifname $LAN tcp dport { 53, 67 } counter name tcp_dns accept
		iifname $LAN udp dport { 53, 67 } counter name udp_dns accept
		# Open the specific ports that we allow
		{% for port in tcpPorts %}
		iifname $FRIENDS tcp dport {{ port }} accept
		{% endfor %}
		{% for port in udpPorts %}
		iifname $FRIENDS udp dport {{ port }} accept
		{% endfor %}

		#iifname $LAN counter name catchall accept comment "Allows LAN traffic and outgoing"
		iifname {{ wanInterface }} ct state { established, related } accept comment "Allows existing connections"
		iifname {{ wanInterface }} icmp type { echo-request, destination-unreachable, time-exceeded } accept comment "Allow some ICMP traffic"
		iifname {{ wanInterface }} counter drop comment "Drop other incoming traffic, and count how much"
		iifname "podman0" ct state { established, related } accept comment "Allows existing connections"
		iifname "podman0" icmp type { echo-request, destination-unreachable, time-exceeded } accept comment "Allow some ICMP traffic"
		iifname "podman0" counter drop comment "Drop other incoming traffic, and count how much"
	}
	chain forward {
		type filter hook forward priority 0; policy drop;
		iifname $LAN oifname {{ wanInterface }} accept comment "Forward LAN to WAN"
		iifname {{ wanInterface }} oifname $LAN ct state established, related accept comment "Allow incoming established traffic"
		iifname $LAN oifname "podman0" accept comment "Forward LAN to WAN"
		iifname "podman0" oifname $LAN ct state established, related accept comment "Allow incoming established traffic"
	}
}

table ip nat {
	chain postrouting {
		type nat hook postrouting priority 100; policy accept;
		oifname { {{ wanInterface }} } masquerade
		oifname "podman0" masquerade
	}
}

table ip6 filter {
	chain input {
		type filter hook input priority 0; policy drop;
	}
	chain forward {
		type filter hook forward priority 0; policy drop;
	}
}
