#!/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 uci = require('simple-uci').cursor()
local unistd = require 'posix.unistd'


local function iface_exists(ifaces)
	if not ifaces then return nil end

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


local lan_ifname = iface_exists(uci:get('network', 'lan', 'ifname'))
local wan_ifname = iface_exists(uci:get('network', 'wan', 'ifname'))

if platform.match('ar71xx', 'generic', {
	'cpe210',
	'cpe510',
	'wbs210',
	'wbs510',
	'airgateway',
	'nanostation-m',
	'nanostation-m-xw',
	'unifi-outdoor-plus',
	'uap-pro',
	'unifiac-pro',
}) then
	lan_ifname, wan_ifname = wan_ifname, lan_ifname
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:save('network')
