local mymodule = {}

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

-- Set variables
local processname = "clamd"
local packagename = "clamav"
local filelist = {"/etc/clamav/clamd.conf", "/etc/clamav/freshclam.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, "ClamAV Status")
end

function mymodule.getstatusdetails()
	return cfe({ type="longtext", value="", label="ClamAV Status Details" })
end

function mymodule.getfilelist()
	local listed_files = {}

	for i,name in ipairs(filelist) do
		local filedetails = posix.stat(name) or {}
		filedetails.filename = name
		table.insert(listed_files, filedetails) 
	end

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

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

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

function mymodule.get_logfile(self, clientdata)
	local files = {}
	local config = format.parse_configfile(fs.read_file(filelist[1]) or "")
	local logfilepath = config.LogFile
	if logfilepath then
		files[#files+1] = {filename=logfilepath}
	end
	if config.LogSyslog then
		files[#files+1] = {facility=config.LogFacility or "LOG_LOCAL6", grep="clamd"}
	end
	config = format.parse_configfile(fs.read_file(filelist[2]) or "")
	logfilepath = config.UpdateLogFile
	if logfilepath then
		files[#files+1] = {filename=logfilepath}
	end
	if config.LogSyslog then
		files[#files+1] = {facility=config.LogFacility or "LOG_LOCAL6", grep="freshclam"}
	end

	return cfe({ type="structure", value=files, label="ClamAV logfiles" })
end

return mymodule
