#!/usr/bin/lua

local site = require 'gluon.site'
local util = require 'gluon.util'

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

local vpn_core = require 'gluon.mesh-vpn'
local _, active_vpn = vpn_core.get_active_provider()

uci:section('network', 'interface', 'mesh_vpn', {
	ifname = vpn_core.get_interface(),
	proto = 'gluon_mesh',
	transitive = true,
	fixed_mtu = true,
	macaddr = util.generate_mac(7),
	mtu = active_vpn.mtu(),
})

uci:save('network')


uci:section('firewall', 'include', 'mesh_vpn_dns', {
	type = 'restore',
	path = '/lib/gluon/mesh-vpn/iptables.rules',
	family = 'ipv4',
})

uci:save('firewall')

-- Inital VPN setup
if not uci:get('gluon', 'mesh_vpn') then
	local enabled = site.mesh_vpn.enabled(false)

	local limit_enabled = site.mesh_vpn.bandwidth_limit.enabled(false)
	local limit_ingress = site.mesh_vpn.bandwidth_limit.ingress()
	local limit_egress = site.mesh_vpn.bandwidth_limit.egress()

	uci:section('gluon', 'mesh_vpn', 'mesh_vpn', {
		enabled = enabled,
		limit_enabled = limit_enabled,
		limit_ingress = limit_ingress,
		limit_egress = limit_egress,
	})
	uci:save('gluon')
end

os.execute('exec /lib/gluon/mesh-vpn/update-config')
