#!/usr/bin/lua

local sys = require "luci.sys"
local fs = require "nixio.fs"
local io = require "io"
local uci_r  = require("luci.model.uci").cursor()

local nm_log_path = "/var/log/nm_log"
local CRON_JOB = "0 0 * * * /usr/sbin/nm_log_save"
local CRON_FILE = "/etc/crontabs/root"
local TAR_GZ_PATH = "/var/log/nm_log.tar.gz"
local LOG_PATH = "/var/log/nm_log"

local bit = require "bit"
local band, bor, lshift, rshift = bit.band, bit.bor, bit.lshift, bit.rshift

local B64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'

local function base64_decode(str)
    local char_map = {}
    for i=1, #B64_CHARS do
        char_map[B64_CHARS:sub(i,i)] = i-1
    end

    str = str:gsub("=*$", "")
    local padding = (#str % 4)
    if padding >0 then
        str = str .. string.rep("A", 4 - padding) 
    end

    local decoded = {}
    for i=1, #str, 4 do
        local a = char_map[str:sub(i,i)] or 0
        local b = char_map[str:sub(i+1,i+1)] or 0
        local c = char_map[str:sub(i+2,i+2)] or 0
        local d = char_map[str:sub(i+3,i+3)] or 0

        local n = bor(lshift(a,18), lshift(b,12), lshift(c,6), d)

        table.insert(decoded, string.char(band(rshift(n,16), 0xFF)))
        table.insert(decoded, string.char(band(rshift(n,8), 0xFF)))
        table.insert(decoded, string.char(band(n, 0xFF)))
    end

    return table.concat(decoded)
end

local function collect_base64_blocks()
    local blocks = {}
    uci_r:foreach("log", "nm_log", function(s)
        for k, v in pairs(s) do
            if k:match("^base64_") then
                table.insert(blocks, {
                    index = tonumber(k:match("^base64_(%d+)")),
                    data = v
                })
            end
        end
    end)
    
    table.sort(blocks, function(a, b) return a.index < b.index end)
    
    local base64_str = ""
    for _, block in ipairs(blocks) do
        base64_str = base64_str .. block.data
    end
    
    return base64_str
end

local function restore_log()
    local base64_str = collect_base64_blocks()
    if #base64_str == 0 then
        print("No base64 log data found in UCI config")
        return false
    end

    -- 使用Lua解码替代系统命令
    local decoded_data = base64_decode(base64_str)
    if #decoded_data == 0 then
        print("Base64 decode failed")
        return false
    end

    -- 直接写入压缩数据
    local tmp_tar = os.tmpname()
    local f = io.open(tmp_tar, "wb")
    if not f then
        print("Failed to create temp file")
        return false
    end
    f:write(decoded_data)
    f:close()

    -- 解压处理
    local ret = sys.exec("tar -xzf "..tmp_tar.." -C / 2>&1")
    os.remove(tmp_tar)
    
    if fs.access(LOG_PATH) then
        print("Log restored successfully to "..LOG_PATH)
        local verify = sys.exec("tar -tzf "..LOG_PATH.." 2>/dev/null")
        --if #verify == 0 then
            --print("Warning: Restored log may be corrupted")
        --end
        return true
    else
        print("Failed to restore log file. tar output: "..ret)
        return false
    end
end

restore_log() 

local file = io.open(nm_log_path, "r")
if file then
    local content = file:read("*all")
    file:close()
    if content == "" then
        os.remove(nm_log_path)
    end
else
end

local found = false
local cron_content = {}


local cron_file_handle = io.open(CRON_FILE, "r")
if cron_file_handle then
    for line in cron_file_handle:lines() do
        table.insert(cron_content, line)
        if line == CRON_JOB then
            found = true
        end
    end
    cron_file_handle:close()
end

if not found then
    table.insert(cron_content, CRON_JOB)
    cron_file_handle = io.open(CRON_FILE, "w")
    if cron_file_handle then
        for _, line in ipairs(cron_content) do
            cron_file_handle:write(line .. "\n")
        end
        cron_file_handle:close()
    end
end

sys.exec("/etc/init.d/cron restart &")