<%
-- Linksys ATA Configuration File Template
local values = ...

--[[ -- Parameters
values["device"]["adminpassword"] = ""
values["device"]["digitmap"] = ""
values["device"]["mac"] = ""
values["device"]["musiconhold"] = ""
values["device"]["registrar"] = ""
values["device"]["sntpserver"] = ""
values["device"]["template"] = "/etc/provisioning/templates/linksysata-template.lua"
values["device"]["timezone"] = ""
values["regX"]["callerid"] = ""
values["regX"]["extension"] = ""
values["regX"]["forwardall"] = ""
values["regX"]["forwardallenable"] = false
values["regX"]["forwardbusy"] = ""
values["regX"]["forwardbusyenable"] = false
values["regX"]["forwardnoanswer"] = ""
values["regX"]["forwardnoanswerenable"] = false
values["regX"]["password"] = ""
-- Unimplemented -- values["services"]["callhistoryenable"] = true
values["services"]["callwaitingenable"] = true
values["services"]["forwarding"] = true
values["services"]["hotlinedestination"] = ""
values["services"]["hotlineenable"] = false
-- Unimplemented -- values["services"]["mailbox"] = ""
-- Unimplemented -- values["services"]["speeddialenable"] = true
--]]

local function yesno ( bool )
	if bool then
		return "Yes"
	else
		return "No"
	end
end

local function xml_elem(elem,value,permissions,i)
	local e = elem
	if i then e = elem.."_"..tostring(i).."_" end
	local output = {"<", e, ' ua="'}
	output[#output+1] = (permissions or "na")..'">'
	if type(value) == "boolean" then
		output[#output+1] = yesno(value)
	elseif value then
		output[#output+1] = value
	end
	output[#output+1] = "</"..e..">"
	io.write(table.concat(output).."\n")
end
%>
<?xml version="1.0" encoding="utf-8"?>

<flat-profile>

<%
xml_elem("Admin_Passwd", values.device.adminpassword, "na")
xml_elem("User_Password", values.device.adminpassword, "na")
xml_elem("HostName", values.reg1.extension, "na")
xml_elem("Primary_NTP_Server", values.device.sntpserver, "na")
xml_elem("CW_Setting", (values.services and values.services.callwaitingenable), "na")

-- Handle Time Zone parameter
--   See http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html
--     TZ variable, with no leading colon
--   Syntax: stdoffset[dst[offset][,start[/time],end[/time]]]
--   Examples: 'GMT0' 'EST5EDT,M3.2.0,M11.1.0' '<GMT+5>5'
--  Parse time zone variable
posixtz = require('posixtz')
local tz = posixtz.parse(values.device.timezone)
if tz then
	-- convert POSIX sign (W of GMT is '+') to Linksys (E of GMT is '+')
	if tonumber(tz.offset.hour) == 0 then
		xml_elem("Time_Zone", "GMT", "na")
	else
		if tz.offset.sign == "-" then
			tz.offset.sign = "+"
		else
			tz.offset.sign = "-"
		end
		xml_elem("Time_Zone", "GMT"..tz.offset.sign..string.format("%02i", tonumber(tz.offset.hour or 0))..":00", "na")
	end

	local function dstrule(t)
		local date, time

		if t.day then
			date = t.month.."/"..t.day.."/0"
		else
			-- POSIX weekday is between 0 (Sun) and 6 (Sat)
			-- Linksys weekday is between 1=Mon, 7=Sun
			if tonumber(t.weekday) == 0 then
				t.weekday = 7
			end
			-- POSIX week is between 1 and 5, where 1st,2nd..4th, and 5=last
			-- Linksys is by day
			if tonumber(t.week) == 5 then
				t.week = -1
			else
				t.week = (t.week * 7)-6
			end
			date = t.month.."/"..t.week.."/"..t.weekday
		end


		-- Handle explicit hour for DST change (posixtz only handles hour for now)
		if t.hour then
			time = string.format("%02i", t.hour)..":00:00"
		else
			time = "2:00:00"
		end

		return date.."/"..time
	end
	
	if tz.dst then
		xml_elem("Daylight_Saving_Time_Enable", "Yes", "na")
		xml_elem("Daylight_Saving_Time_Rule", "start="..dstrule(tz.dst.start)..";end="..dstrule(tz.dst.stop)..";save=1", "na")
	else
		xml_elem("Daylight_Saving_Time_Enable", "No", "na")
	end
end

for pg, pg_t in pairs(values) do
	-- Is it of the form regX ?
	local num = string.match(pg, 'reg(%d+)')
	if num then
		if pg_t.extension ~= "" then
			xml_elem("Line_Enable", "Yes", "na", num)
			xml_elem("MOH_Server", values.device.musiconhold, "na", num)
			xml_elem("Proxy", values.device.registrar, "na", num)
			xml_elem("Call_Waiting_Serv", (values.services and values.services.callwaitingenable), "na", num)
			if values.services and values.services.hotlineenable then
				-- Tested and found delay of 0 didn't work, so using 1 second
				-- Need to escape < and >
				xml_elem("Dial_Plan", "( P1&lt;:"..values.services.hotlinedestination.."&gt; )", "na", num)
			elseif values.device and values.device.digitmap and values.device.digitmap ~= "" then
				xml_elem("Dial_Plan", "( "..values.device.digitmap.." )", "na", num)
			else
				xml_elem("Dial_Plan", "( x. )", "na", num)
			end

			if pg_t.callerid == "" then
				pg_t.callerid = pg_t.extension
			end
			xml_elem("Display_Name", pg_t.callerid, "na", num)
			xml_elem("User_ID", pg_t.extension, "na", num)
			xml_elem("Password", pg_t.password, "na", num)

			local forwarding = {	{param="forwardall", xml="Cfwd_All_"},
						{param="forwardbusy", xml="Cfwd_Busy_"},
						{param="forwardnoanswer", xml="Cfwd_No_Ans_"} }
			for i,f in ipairs(forwarding) do
				if values.services.forwarding and pg_t[f.param.."enable"] then
					xml_elem(f.xml.."Serv", "Yes", "na", num)
					xml_elem(f.xml.."Dest", pg_t[f.param], "na", num)
				else
					xml_elem(f.xml.."Serv", "No", "na", num)
					xml_elem(f.xml.."Dest", "", "na", num)
				end
			end
		else
			-- Cannot disable the lines, or check-sync will not work, just set User ID to ""
			xml_elem("Line_Enable", "Yes", "na", num)
			xml_elem("User_ID", "", "na", num)
		end
	end
end %>

</flat-profile>
