#!/usr/bin/lua

local sysconfig = require 'gluon.sysconfig'

-- Are we already set up?
if sysconfig.lan_ifname or sysconfig.wan_ifname then
	os.exit(0)
end


local platform = require 'gluon.platform'
local site = require 'gluon.site'

local json = require 'jsonc'
local uci = require('simple-uci').cursor()
local unistd = require 'posix.unistd'

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

local function iface_exists(ifaces)
	if not ifaces then return nil end
	local ifnames = table.concat(ifaces, ' ')

	for _, iface in ipairs(ifaces) do
		if unistd.access('/sys/class/net/' .. iface:gsub('%..*$', '')) then
			return ifnames
		end
	end
end

local lan_data = network_data.lan or {}
local wan_data = network_data.wan or {}

local lan_interfaces = lan_data.ports
local wan_interfaces = wan_data.ports

-- In case we have a single port for either WAN or LAN,
-- add it to the respective empty table, as devices and
-- ports is XOR in board.json

if lan_data.device ~= nil then
	lan_interfaces = {lan_data.device}
end

if wan_data.device ~= nil then
	wan_interfaces = {wan_data.device}
end

local lan_ifname = iface_exists(lan_interfaces)
local wan_ifname = iface_exists(wan_interfaces)

if platform.match('lantiq') then
	local switch_data = board_data.switch or {}
	local switch0_data = switch_data.switch0 or {}
	local roles_data = switch0_data.roles or {}
	for _, role_data in ipairs(roles_data) do
		if role_data.role == 'wan' then
			wan_ifname = iface_exists(role_data.device)
			break
		end
	end
end

if wan_ifname and lan_ifname then
	sysconfig.wan_ifname = wan_ifname
	sysconfig.lan_ifname = lan_ifname
else
	local single_ifname = lan_ifname or wan_ifname
	if site.single_as_lan(false) then
		sysconfig.lan_ifname = single_ifname
	else
		sysconfig.wan_ifname = single_ifname
	end
end


uci:delete('network', 'lan')
uci:delete('network', 'wan')

uci:delete_all('network', 'device')

uci:save('network')
