<?xml version="1.0" standalone="yes"?>

<%
-- CyberData Intercom Configuration File Template
local values = ...

xml = require("LuaXml")

local InitFile = "/var/www/provisioning/htdocs/CyberData/init.cfg"

local function findSection(xmlobj, name)
	-- Cannot use xmlobj:find() because we don't want recursion
	for i,s in ipairs(xmlobj) do
		if s:tag() == name then
			return s
		end
	end
	return null
end

local function findOrAppendSection(xmlobj, name)
	return findSection(xmlobj, name) or xmlobj:append(name)
end

local function setValue(xmlobj, name, value)
	if value then
		findOrAppendSection(xmlobj, name)[1] = value
	end
end

local function yesno(xmlobj, name, value)
	if value ~= nil then
		if (value == false) then
		value = "No"
		elseif (value == true) then
		value = "Yes"
		end
		setValue(xmlobj, ''..name..'', ''..value..'')
	end
end

-- Load the initial config
local init_cfg
local res, err = pcall(function()
	init_cfg = xml.load(InitFile)
end)
if not res and err then
	init_cfg = xml.new("specific")
end

-- <IPSettings>

-- <SIPSettings>

if values.reg1 then
	local sipsettings = findOrAppendSection(init_cfg, "SIPSettings")
	if values.device then
		setValue(sipsettings, "SIPServer", values.device.registrar)
	end
	setValue(sipsettings, "SIPUserID", values.reg1.extension)
	setValue(sipsettings, "SIPAuthID", values.reg1.extension)
	setValue(sipsettings, "SIPAuthPassword", values.reg1.password)
	setValue(sipsettings, "DialoutExtension0", values.reg1.hotlinedestination)
	setValue(sipsettings, "DialoutID0", values.reg1.callerid)

end

-- <DeviceSettings>

if values.device then
	local DeviceSettings = findOrAppendSection(init_cfg, "DeviceSettings")
	setValue(DeviceSettings, "SpeakerVolume", values.device.cyberspeakervolume)
	setValue(DeviceSettings, "AdminPassword", values.device.adminpassword)
	setValue(DeviceSettings, "RingVolume", values.device.cyberringvolume)
	setValue(DeviceSettings, "MicGain", values.device.cybermicgain)
	yesno (DeviceSettings, "ActivateRelayWithDTMF", values.device.activaterelaywithdtmf)
	setValue(DeviceSettings, "DTMFActivationCode", values.device.dtmfactivationcode)
	setValue(DeviceSettings, "DTMFActivationDuration", values.device.dtmfactivationduration)
	yesno (DeviceSettings, "ActivateRelayDuringRing", values.device.activaterelayduringring)
	yesno (DeviceSettings, "ActivateRelayDuringCall", values.device.activaterelayduringcall)
end

-- <ButtonSettings>

if values.device then
	local ButtonSettings = findOrAppendSection(init_cfg, "ButtonSettings")
	yesno (ButtonSettings, "PlayToneWhileRelayActive", values.device.playtonewhilerelayactive)
end

-- <ClockSettings>

if values.device then
	local clocksettings = findOrAppendSection(init_cfg, "ClockSettings")
	setValue(clocksettings, "NTPServer", values.device.sntpserver)
	setValue(clocksettings, "NTPTimezone", values.device.timezone)
end

-- init_cfg:save("TEST-cyberdata.xml")

print(init_cfg)
%>
