local uci = require("uci").cursor()
local fs = require("nixio.fs")


-- 保存流量数据的文件路径
local traffic_file = "/tmp/mytraffic_traffic_data"
-- 获取网络接口
function get_interfaces()
    local interfaces = {}
    uci:foreach("network", "interface", function(section)
        table.insert(interfaces, section['.name'])
    end)
    return interfaces
end

-- 读取持久化的流量数据
local function read_saved_traffic()
    if fs.access(traffic_file) then
        local data = fs.readfile(traffic_file)
        return data and loadstring("return " .. data)() or {rx_bytes = 0, tx_bytes = 0}
    end
    return {rx_bytes = 0, tx_bytes = 0}
end


-- 保存当前累计的流量数据
local function save_traffic(data)
    fs.writefile(traffic_file, "{" .. string.format("rx_bytes = %d, tx_bytes = %d", data.rx_bytes, data.tx_bytes) .. "}")
end

-- 统计流量并累计
function get_traffic(interface)
    local result = {
        rx_bytes = 0,
        tx_bytes = 0
    }

    -- 打开 /proc/net/dev 文件
    local file = io.open("/proc/net/dev", "r")
    if not file then
        return result
    end

    -- 遍历文件的每一行
    for line in file:lines() do
        -- 查找指定接口的流量数据
        if line:find(interface .. ":") then
            -- 使用模式匹配提取接收和发送的字节数
            local rx, tx = line:match(interface .. ":%s*(%d+)%s*%d+%s*%d+%s*%d+%s*%d+%s*%d+%s*%d+%s*(%d+)")
            result.rx_bytes = tonumber(rx) or 0
            result.tx_bytes = tonumber(tx) or 0
            break
        end
    end

    -- 关闭文件
    file:close()

    -- 读取保存的流量数据
    local saved_traffic = read_saved_traffic()

    -- 累计当前流量和之前保存的流量
    result.rx_bytes = result.rx_bytes + saved_traffic.rx_bytes
    result.tx_bytes = result.tx_bytes + saved_traffic.tx_bytes

    -- 保存更新后的流量数据
    save_traffic(result)

    return result
end


-- 设置并保存配置
function set_config(interface, max_traffic, auto_reset, shutdown)
    uci:set("mytraffic", "settings", "interface", interface)
    uci:set("mytraffic", "settings", "max_traffic", max_traffic)
    uci:set("mytraffic", "settings", "auto_reset", auto_reset)
    uci:set("mytraffic", "settings", "shutdown", shutdown)
    uci:commit("mytraffic")
end

-- 检查并执行流量超限处理
function check_and_shutdown(interface, max_traffic)
    local traffic = get_traffic(interface)
    local total_traffic = (traffic.rx_bytes + traffic.tx_bytes) / (1024 * 1024 * 1024)  -- 转换为GB

    if total_traffic > max_traffic then
        os.execute("ifdown " .. interface)
    end
end


-- 获取配置
function get_config()
    return uci:get_all("mytraffic", "settings")
end
