#!/usr/bin/lua5.2

local posix = require 'posix'
local aac = require 'aaudit.common'
local aas = require 'aaudit.server'

local pullafter = aas.serverconfig["pull-after"] or 24*60*60
local warnafter = aas.serverconfig["warn-after"] or 4*24*60*60

local function dorepo(repodir)
	-- Check if it's time to update
	local repoconf = aas.loadrepoconfig(repodir)
	local stampfile = ("%s/lastcheck"):format(repodir)
	local mtime = posix.stat(stampfile, "mtime") or 0

	if os.time() > mtime + pullafter then
		-- Pull for changes
		local req = {
			command = "commit",
			target_address = repoconf.address,
			message = "Unexpected configuration change",
			local_change = true,
		}
		local ret, msg = aas.handle(req)
		print(("Updating repository %s -> %s: %s"):format(repodir, repoconf.address, msg))
		mtime = posix.stat(stampfile, "mtime") or 0
	end

	return mtime, repoconf.address
end

local home = os.getenv("HOME")
local outdated = {"List of unreachable monitored hosts:"}
for _, repodir in ipairs(posix.glob(("%s/*.git"):format(home))) do
	local mtime, address = dorepo(repodir)
	if os.time() > mtime + warnafter then
		table.insert(outdated, address)
	end
end

if #outdated > 1 and aas.serverconfig["notify-unreachables"] then
	aas.sendemail {
		to = aas.serverconfig["notify-unreachables"],
		subject = "aaudit report of unreachable hosts",
		message = table.concat(outdated, "\n"),
	}
end
