#!/usr/bin/lua

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

local sysconfig = require 'gluon.sysconfig'
local util = require 'gluon.util'
local json = require 'jsonc'

local function get_network_mac(name)
	local board_data = json.load('/etc/board.json')
	local network_data = (board_data or {}).network

	if network_data == nil then
		return nil
	end

	local ifdata = network_data[name] or {}
	return ifdata.macaddr
end

local wan = uci:get_all('network_gluon-old', 'wan') or {}
local wan6 = uci:get_all('network_gluon-old', 'wan6') or {}

uci:section('network', 'interface', 'loopback', {
	ifname = 'lo',
	proto = 'static',
	ipaddr = '127.0.0.1',
	netmask = '255.0.0.0',
})

local wan_proto = 'dhcp'

if sysconfig.gluon_version and wan.proto ~= nil then
	-- Only restore WAN proto in case this is an upgrade
	wan_proto = wan.proto
end

uci:section('network', 'interface', 'wan', {
	proto = wan_proto,
	ipaddr = wan.ipaddr,
	netmask = wan.netmask,
	gateway = wan.gateway,
	macaddr = get_network_mac('wan'),
	ifname = util.get_role_interfaces(uci, 'uplink'),
	type = 'bridge',
	igmp_snooping = true,
	multicast_querier = false,
	peerdns = false,
	auto = true,
})

uci:section('network', 'interface', 'wan6', {
	proto = wan6.proto or 'dhcpv6',
	ip6addr = wan6.ip6addr,
	ip6gw = wan6.ip6gw,
	ifname = 'br-wan',
	peerdns = false,
	ip6table = 1,
	sourcefilter = false,
	reqprefix = 'no',
})

uci:section('network', 'rule6', 'wan6_lookup', {
	mark = '0x01/0x01',
	lookup = 1,
})

uci:section('network', 'route6', 'wan6_unreachable', {
	type = 'unreachable',
	interface = 'loopback',
	target = '::/0',
	gateway = '::',
	table = 1,
	metric = 65535,
})

uci:save('network')


uci:section('firewall', 'rule', 'wan_igmp', {
	name = 'Allow-IGMP',
	src = 'wan',
	proto = 'igmp',
	family = 'ipv4',
	target = 'ACCEPT',
})

uci:section('firewall', 'rule', 'wan_mld', {
	name = 'Allow-MLD',
	src = 'wan',
	proto = 'icmp',
	src_ip = 'fe80::/10',
	icmp_type = { '130/0', '131/0', '132/0', '143/0', },
	family = 'ipv6',
	target = 'ACCEPT',
})

uci:save('firewall')
