local mymodule = {}

-- Load libraries
modelfunctions = require("modelfunctions")
fs = require("acf.fs")
format = require("acf.format")

-- Set variables
local processname = "lighttpd"
local packagename = "lighttpd"
local filelist = {"/etc/lighttpd/lighttpd.conf", "/etc/lighttpd/mod_cgi.conf", "/etc/lighttpd/mod_fastcgi.conf", "/etc/lighttpd/mod_fastcgi_fpm.conf"}

local path = "PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin "

-- ################################################################################
-- LOCAL FUNCTIONS

-- ################################################################################
-- PUBLIC FUNCTIONS

function mymodule.get_startstop(self, clientdata)
        return modelfunctions.get_startstop(processname)
end

function mymodule.startstop_service(self, startstop, action)
        return modelfunctions.startstop_service(startstop, action)
end

function mymodule.getstatus()
	return modelfunctions.getstatus(processname, packagename, "Lighttpd Status")
end

function mymodule.getfilelist()
	local listed_files = {}

	for i,name in ipairs(filelist) do
		local filedetails = fs.stat(name) or {}
		table.insert ( listed_files , {filename=name, mtime=filedetails.mtime or "---", filesize=filedetails.size or "0"} )
	end

	table.sort(listed_files, function (a,b) return (a.filename < b.filename) end )

	return cfe({ type="list", value=listed_files, label="Lighttpd File List" })
end

function mymodule.getfiledetails(filename)
	return modelfunctions.getfiledetails(filename, filelist)
end

function mymodule.updatefiledetails(self, filedetails)
	return modelfunctions.setfiledetails(self, filedetails, filelist)
end

function mymodule.getlogfile ()
	local files = {}
	local logfilepath = format.parse_configfile(fs.read_file(filelist[1]) or "").LogFile
	if not logfilepath then
		files[#files+1] = {path = "/var/log/lighttpd/access.log"}
	else
		files[#files+1] = {path=logfilepath}
	end
	logfilepath = format.parse_configfile(fs.read_file(filelist[2]) or "").UpdateLogFile
	if not logfilepath then
		files[#files+1] = {path = "/var/log/lighttpd/error.log"}
	else
		files[#files+1] = {path=logfilepath}
	end
	return cfe({ value=files, label="Lighttpd logfiles" })
end

return mymodule
