#!/usr/bin/lua

local uci = require('simple-uci').cursor()
local site = require('gluon.site')

-- Allow respondd port on WAN to allow resolving neighbours over mesh-on-wan
uci:section('firewall', 'rule', 'wan_respondd', {
	name = 'wan_respondd',
	src = 'wan',
	src_ip = 'fe80::/64',
	dest_port = '1001',
	proto = 'udp',
	target = 'ACCEPT',
})

-- Allow respondd-access for local clients
uci:section('firewall', 'rule', 'client_respondd', {
	name = 'client_respondd',
	src = 'loc_client',
	src_ip = 'fe80::/64',
	dest_port = '1001',
	proto = 'udp',
	target = 'ACCEPT',
})

-- Allow respondd-access from within the mesh
uci:section('firewall', 'rule',  'mesh_respondd_ll', {
	name = 'mesh_respondd_ll',
	src = 'mesh',
	src_ip = 'fe80::/64',
	dest_port = '1001',
	proto = 'udp',
	target = 'ACCEPT',
})

uci:section('firewall', 'rule',  'mesh_respondd_siteprefix', {
	name = 'mesh_respondd_siteprefix',
	src = 'mesh',
	src_ip = site.prefix6(),
	dest_port = '1001',
	proto = 'udp',
	target = 'ACCEPT',
})

uci:delete_all('firewall', 'rule', function(rule)
	return rule['.name']:find('^mesh_respondd_extraprefix')
end)

for idx, prefix in ipairs(site.extra_prefixes6({})) do
	uci:section('firewall', 'rule',  'mesh_respondd_extraprefix' .. idx, {
		name = 'mesh_respondd_extraprefix' .. idx,
		src = 'mesh',
		src_ip = prefix,
		dest_port = '1001',
		proto = 'udp',
		target = 'ACCEPT',
	})
end

uci:save('firewall')
