-- Created by hongbe.he@lnxall.com
-- lib of lua for individual log control
-- 2025/10/31

local posix   = require "posix"
local invoker = require "invoker"

local _M = {}

local gfmt = string.format

local g_filp = nil
local g_date = nil
local g_path = nil

local g_maxlogn = 15

function _M.set(maxlogn)
	if maxlogn > 0 then
		g_maxlogn = maxlogn
		io.stdout:write(gfmt('Set max num of logs: %d\n', g_maxlogn))
		io.stdout:flush()
		return true
	end
	return false
end

function _M.open(path)
	if g_filp then return false end

	g_filp = io.open(path, 'a+')
	if not g_filp then
		io.stderr:write(gfmt("Error, cannot open %s\n", path))
		io.stderr:flush()
		return false
	end

	g_path = path
	g_date = os.date('%Y%m%d')
	return true
end

function _M.close()
	if g_filp then
		g_filp:close()
		g_filp = nil
		g_path = nil
		g_date = nil
		return true
	end

	return false
end

function _M.write(data)
	if not g_filp then return false end

	g_filp:write(data)
	g_filp:flush()
	return true
end

function _M.writeln(data)
	local ldata = tostring(data)
	if not string.match(ldata, '\n$') then
		ldata = ldata .. '\n'
	end

	return _M.write(ldata)
end

function _M.try_rotate()
	if not g_path then return false end

	local mode, size = invoker.statfile(g_path)
	if mode ~= "regular" or size == 0 then
		return false
	end

	local today = os.date('%Y%m%d')
	if g_date ~= today then
		local old_path = g_path
		local new_path = g_path .. '_' .. g_date
		_M.close()
		invoker.rename(old_path, new_path)
		io.stdout:write(gfmt('log rotate: %s => %s\n', old_path, new_path))

		invoker.unlink(old_path)
		g_path = old_path
		_M.open(g_path)
	end

	local globuf = invoker.glob(g_path .. '*')
	if #globuf > g_maxlogn then
		table.sort(globuf)
		invoker.unlink(globuf[2])

		io.stdout:write(gfmt('removed old log: %s\n', globuf[2]))
	end

	io.stdout:flush()
	return true
end

return _M
