#!/bin/sh

if [ -e "/etc/config/ucitrack" ]; then
    uci -q batch <<-EOF
 		delete ucitrack.@passwall[-1]
		add ucitrack passwall
		set ucitrack.@passwall[-1].init=passwall
		delete ucitrack.@passwall_server[-1]
		add ucitrack passwall_server
		set ucitrack.@passwall_server[-1].init=passwall_server
		commit ucitrack
EOF
fi

uci -q batch <<-EOF
	delete firewall.passwall
	set firewall.passwall=include
	set firewall.passwall.type='script'
	set firewall.passwall.path='/var/etc/passwall.include'

	delete firewall.passwall_server
	set firewall.passwall_server=include
	set firewall.passwall_server.type='script'
	set firewall.passwall_server.path='/var/etc/passwall_server.include'

	set dhcp.@dnsmasq[0].localuse=1
	commit dhcp
	set uhttpd.main.max_requests=50
	commit uhttpd
EOF

if [ -x "/sbin/fw3" ]; then
	uci -q set firewall.passwall.reload='1'
	uci -q set firewall.passwall_server.reload='1'
else
	uci -q delete firewall.passwall.reload
	uci -q delete firewall.passwall.fw4_compatible
	uci -q delete firewall.passwall_server.reload
	uci -q delete firewall.passwall_server.fw4_compatible
fi
uci commit firewall

[ ! -s "/etc/config/passwall" ] && cp -f /usr/share/passwall/0_default_config /etc/config/passwall

chmod +x /usr/share/passwall/*.sh

[ "$(uci -q get passwall.@global_xray[0].sniffing)" == "1" ] && [ "$(uci -q get passwall.@global_xray[0].route_only)" != "1" ] && uci -q set passwall.@global_xray[0].sniffing_override_dest=1
uci -q delete passwall.@global_xray[0].sniffing
uci -q delete passwall.@global_xray[0].route_only
uci -q commit passwall

sed -i "s#add_from#group#g" /etc/config/passwall 2>/dev/null

rm -f /tmp/luci-indexcache /tmp/luci-indexcache.*
rm -rf /tmp/luci-modulecache/
killall -HUP rpcd 2>/dev/null

exit 0
