#!/opt/lnxall_app/bin/lua

-- Created by jiaqiang.ye@lnxall.com
-- Simple First Network detection
-- 2026/01/23

local uci     = require "uci"
local invoker = require "invoker"
local gfmt    = string.format

local function first_ndev()
	local okay, output = invoker.invoke(invoker.OUTPUT, "ip", "route", "show")
	if not okay or type(output) ~= "string" then
		io.stderr:write("Error, command has failed: ip route show\n")
		io.stderr:flush()
		return nil
	end

	local dftm, dftn = {}, 0
	for line in string.gmatch(output, "[^\r\n]+") do
		if string.find(line, "default via", 1, true) then
			local metric = string.match(line, "metric%s+(%d+)")
			if metric then metric = tonumber(metric) end
			if type(metric) ~= "number" then metric = 0 end
			local ndev = string.match(line, "%s+dev%s+([^%s]+)%s")
			if ndev and invoker.invoke(invoker.NOSTDIO, "ip", "link", "show", "dev", ndev) == 0 then
				dftn = dftn + 1
				dftm[dftn] = { ["device"] = ndev, ["metric"] = metric }
			end
		end
	end

	if dftn == 0 then return nil end
	if dftn >= 2 then
		table.sort(dftm, function (fa, fb)
			return fa.metric < fb.metric
		end)
	end
	return dftm[1].device
end

local function mainfunc()
	local ndev = first_ndev()
	if not ndev then
		io.stdout:write("NONE\n")
		io.stdout:flush()
		return false
	end

	if ndev == "br-lan" then
		io.stdout:write("lan\n")
		io.stdout:flush()
		return true
	end

	local xuci = uci.cursor("/etc/config")
	local wan_list = {
		["wwan"]      = "4G",
		["wifiwan"]   = "WiFi",
		["wan"]       = "1",
		["wan1"]      = "2",
		["wan2"]      = "3",
		["wan3"]      = "4",
		["wan4"]      = "5",
		["wan5"]      = "6",
		["wan6"]      = "7",
		["wan7"]      = "8",
		["wan8"]      = "9",
	}

	for wan, which in pairs(wan_list) do
		if xuci:get("network", wan, "device") == ndev then
			io.stdout:write(gfmt("%s\n", which))
			io.stdout:flush()
			xuci:close(); xuci = nil
			return true
		end
	end

	xuci:close(); xuci = nil
	io.stdout:write("NONE\n")
	io.stdout:flush()
	return false
end
os.exit(mainfunc() and 0 or 1)
