-- This is the script run after deleting a device (and all of its params)
local functions, olddevice, oldparams = ...

posix = require("posix")

local root = "/var/www/provisioning/htdocs/"

--functions.logevent("got to delete_device script")

-- First, we delete the associated config files for Polycom with valid MAC (not blank or all 0's)
if oldparams.value.device and string.match(oldparams.value.device.label, "Polycom") and oldparams.value.device.value.mac and string.match(oldparams.value.device.value.mac.value, "[1-9A-F]") then
	--functions.logevent("Deleting files for "..oldparams.value.device.value.mac.value)
	local path = root.."Polycom/"
	if posix.stat(path, "type") == "directory" then
		for d in posix.files(path) do
			if string.match(d, string.lower(oldparams.value.device.value.mac.value)) and posix.stat(path..d, "type") == "regular" then
				--functions.logevent("deleting "..path..d)
				os.remove(path..d)
			end
		end
	end
end

-- We'll handle the deleting of the device by handling the resulting changing of the params
-- First, have to create a new set of params (with blank extensions)
local duplicatestructure
duplicatestructure = function(value, saved)
        saved = saved or {}
	if type(value) == "table" then
		if saved[value] then
			return saved[value]
		else
			local output = {}
			saved[value] = output
			for k,v in pairs(value) do
				output[k] = duplicatestructure(v, saved)
			end
			return output
		end
	else
		return value
	end
end

local params = duplicatestructure(oldparams)
for name,val in pairs(params.value) do
        if string.match(name, "^reg") then
		params.value[name].value.extension.value = ""
	end
end

-- Then call the other script
local f
local env = {}
setmetatable (env, {__index = _G})
local IS_52_LOAD = pcall(load, '')
if IS_52_LOAD then
	f = loadfile("/etc/provisioning/update_device_params.lua", "bt", env)
else
	-- loadfile loads into the global environment
	-- so we set env 0, not env 1
	setfenv (0, env)
	f = loadfile("/etc/provisioning/update_device_params.lua")
	setfenv (0, _G)
end
if (f) then f(functions, params, oldparams) end
