#!/usr/bin/utpl -S

{%-
	import { cursor } from 'uci';

	const cfgname = 'homeproxy';
	const uci = cursor();
	uci.load(cfgname);

	const routing_mode = uci.get(cfgname, 'config', 'routing_mode') || 'bypass_mainland_china',
	      proxy_mode = uci.get(cfgname, 'config', 'proxy_mode') || 'redirect_tproxy';

	let outbound_node, tun_name;
	if (match(proxy_mode, /tun/)) {
		if (routing_mode === 'custom')
			outbound_node = uci.get(cfgname, 'routing', 'default_outbound') || 'nil';
		else
			outbound_node = uci.get(cfgname, 'config', 'main_node') || 'nil';

		if (outbound_node !== 'nil')
			tun_name = uci.get(cfgname, 'infra', 'tun_name') || 'singtun0';
	}

	const server_enabled = uci.get(cfgname, 'server', 'enabled');
	let auto_firewall = '0';
	if (server_enabled === '1')
		auto_firewall = uci.get(cfgname, 'server', 'auto_firewall') || '0';

-%}

{% if (tun_name): %}
chain forward {
	oifname {{ tun_name }} counter accept comment "!{{ cfgname }}: accept tun forward"
}
{% endif %}

{% if (tun_name || auto_firewall === '1'): %}
chain input {
	{% if (tun_name): %}
	iifname {{ tun_name }} counter accept comment "!{{ cfgname }}: accept tun input"
	{% endif %}
{%
	if (auto_firewall === '1')
		uci.foreach(cfgname, 'server', (s) => {
			if (s.enabled !== '1')
				return;

			let proto = s.network || '{ tcp, udp }';
			printf('	meta l4proto %s th dport %s counter accept comment "!%s: accept server %s"\n',
				proto, s.port, cfgname, s['.name']);
		});
%}
}
{% endif %}
