#!/bin/sh

zero_enable="$(uci get zerotier.sample_config.enabled)"
[ "$zero_enable" -eq "1" ] || exit 1

count=0
[ -f "/tmp/zero.log" ] && {
	while [ -z "$(ifconfig | grep 'zt' | awk '{print $1}')" ]
	do
		sleep 2
		let count++
		[ "$count" -lt 5 ] || exit 19
	done
}

nft_incdir="/usr/share/nftables.d/chain-pre"
rm -f "$nft_incdir/input/zerotier.nft" "$nft_incdir/forward/zerotier.nft" "$$nft_incdir/srcnat/zerotier.nft"

nat_enable="$(uci get zerotier.sample_config.nat)"
[ "$nat_enable" -eq "1" ] && {
	[ -d "$nft_incdir/input" ] || mkdir -p "$nft_incdir/input"
	[ -d "$nft_incdir/forward" ] || mkdir -p "$nft_incdir/forward"
	[ -d "$nft_incdir/srcnat" ] || mkdir -p "$nft_incdir/srcnat"
	for i in $(ifconfig | grep 'zt' | awk '{print $1}')
	do
		ip_segment="$(ip route | grep "dev $i proto kernel" | awk '{print $1}')"
		echo "iifname $i counter accept comment \"!fw4: Zerotier allow inbound $i\"" >> "$nft_incdir/input/zerotier.nft"
		echo "iifname $i counter accept comment \"!fw4: Zerotier allow inbound forward $i\"" >> "$nft_incdir/forward/zerotier.nft"
		echo "oifname $i counter accept comment \"!fw4: Zerotier allow outbound forward $i\"" >> "$nft_incdir/forward/zerotier.nft"
		echo "oifname $i counter masquerade comment \"!fw4: Zerotier $i outbound postrouting masq\"" >> "$nft_incdir/srcnat/zerotier.nft"
		[ -z "$ip_segment" ] || echo "ip saddr $ip_segment counter masquerade comment \"!fw4: Zerotier $ip_segment postrouting masq\"" >> "$nft_incdir/srcnat/zerotier.nft"
	done
	echo "zt interface rules added!" > "/tmp/zero.log"
	uci -q set firewall.@defaults[0].auto_includes="1"
	uci -q commit firewall
	fw4 reload
}
