#!/usr/bin/env lua

--[[
    Internet detector daemon for OpenWrt.
    Dependencies:
    - lua
    - libuci-lua
    (с) 2025 gSpot
--]]

local InternetDetector = require("internet-detector.main")

--  Move this block up BEFORE it's used
local function getopt(args, options)
    local opt = {}
    local index = 1

    while index <= #args do
        local arg = args[index]
        if arg:sub(1, 1) == "-" then
            local key = arg:sub(2)
            if options:find(key) then
                if index + 1 <= #args and args[index + 1]:sub(1, 1) ~= "-" then
                    opt[key] = args[index + 1]
                    index = index + 1
                else
                    opt[key] = true
                end
            else
                print("Error! Unrecognized option: " .. arg)
                os.exit(1)
            end
        end
        index = index + 1
    end

    return opt
end

-- Help function (can stay where it is)
local function help()
    return table.concat({
        string.format("Usage: %s -a daemon -i <UCI instance> | ...", arg[0]),
        " -a ARG  action: daemon | nodaemon | debug | stop",
        " -i ARG  instance: UCI instance name",
        " -S      status",
        " -I      inet status",
        " -U      uipoll",
        " -h      print this help text"
    }, "\n")
end

--  Now this will work
local options = getopt(arg, "a:i:SIUh")
-- ... rest of your logic ...

local action = options.a
local instance = options.i
local params = {}

for k, v in pairs(options) do
    if k ~= "a" and k ~= "i" then
        table.insert(params, k)
    end
end

if action == "stop" then
    InternetDetector:stop()
elseif action then
    if not instance then
        print("Error! Instance not specified [-i]")
        os.exit(1)
    end
    if action == "daemon" then
        if InternetDetector:setServiceConfig(instance) then
            InternetDetector:daemon()
        else
            os.exit(126)
        end
    elseif action == "nodaemon" then
        if InternetDetector:setServiceConfig(instance) then
            InternetDetector:noDaemon()
        else
            os.exit(126)
        end
    elseif action == "debug" then
        if InternetDetector:setServiceConfig(instance) then
            InternetDetector.debug = true
            InternetDetector:noDaemon()
        else
            os.exit(126)
        end
    else
        print("Error! Wrong action [-a]")
        os.exit(1)
    end
else
    if params[1] == "S" then
        print(InternetDetector:status())
    elseif params[1] == "I" then
        print(InternetDetector:inetStatus())
    elseif params[1] == "U" then
        if InternetDetector:status() == "stopped" then
            os.exit(126)
        else
            InternetDetector:setSIGUSR()
            print(InternetDetector:inetStatus())
        end
    elseif params[1] == "h" then
        print(help())
    else
        print(help())
        os.exit(1)
    end
end

os.exit(0)

