#!/bin/bash
# Beradesk dinleme portlarina yalnizca ozel IPv4 aglardan yeni baglanti kabul eder.
# SSH ve diger servislere dokunmaz. nft yoksa sessizce cikar.
set -u

TABLE=beradesk_in

clear_rules() {
	if command -v nft >/dev/null 2>&1; then
		nft delete table inet "$TABLE" >/dev/null 2>&1 || true
	fi
}

if [ "${1:-}" = "--clear" ]; then
	clear_rules
	exit 0
fi

if ! command -v nft >/dev/null 2>&1; then
	echo "beradesk-firewall-sync: nft yok, gelen ag siniri uygulanmadi." >&2
	exit 0
fi
if ! command -v ss >/dev/null 2>&1; then
	echo "beradesk-firewall-sync: ss yok, gelen ag siniri uygulanmadi." >&2
	exit 0
fi

ports=""
i=0
while [ "$i" -lt 8 ]; do
	ports=$(ss -H -lntup 2>/dev/null | awk '
		/beradesk/ {
			n = split($5, a, ":")
			p = a[n]
			if (p ~ /^[0-9]+$/) print p
		}
	' | sort -u)
	if [ -n "$ports" ]; then
		break
	fi
	i=$((i + 1))
	sleep 1
done

clear_rules
if [ -z "$ports" ]; then
	exit 0
fi

nft add table inet "$TABLE"
nft add chain inet "$TABLE" input '{ type filter hook input priority 0; policy accept; }'
for p in $ports; do
	nft add rule inet "$TABLE" input ip saddr != '{ 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 127.0.0.0/8 }' tcp dport "$p" ct state new drop
	nft add rule inet "$TABLE" input ip saddr != '{ 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 127.0.0.0/8 }' udp dport "$p" ct state new drop
done
exit 0
