#!/usr/bin/env lua
local e=require("uci")local e=e.cursor()local n=require("ubus")local r=n.connect()if not r then
error("Failed to connect to ubusd")end
local c={on="off",off="on"}local a={on='1',off='0'}local function i(n,e)if(e~=nil)then
for t,e in pairs(e)do
if e==n then
return true
end
end
end
return false
end
function get_all_profiles(n)e:foreach("mmpbx","service",function(e)if(e.type=="DND")then
local e=e["profile"]if#e>=1 then
for t,e in ipairs(e)do
n[#n+1]=e
end
end
end
end)end
function scan_for_profile_with_schedule(d,o)e:foreach("tod","action",function(n)local t=nil
if((n.activedaytime~=nil)and(n.object:match("^voicednd")))then
t=n.object:match("^voicednd%.(.*)$")if(t~=nil)then
e:foreach("tod","voicednd",function(e)if(e[".name"]==t)then
for n,e in ipairs(e.profile)do
d[#d+1]=e
end
end
end)end
elseif((n.activedaytime==nil)and(n.object:match("^voicednd")))then
t=n.object:match("^voicednd%.(.*)$")if(t~=nil)then
e:foreach("tod","voicednd",function(e)if(e[".name"]==t)then
for n,e in ipairs(e.profile)do
o[#o+1]=e
end
end
end)end
end
end)end
function update_current_state(o,t)r:send("mmpbx.profile.dnd",{profile=o,dnd=t})e:foreach("mmpbx","service",function(n)if(n["type"]=="DND")and((i(o,n["profile"]))==true)then
current_state=e:get("mmpbx",n['.name'],"activated")if(current_state~=nil)and(current_state~=a[t])then
e:set("mmpbx",n['.name'],"activated",a[t])end
end
end)e:commit("mmpbx")end
function notify_new_state()e:load("tod")e:load("mmpbx")local r={}local n={}local t={}local l={}local o=e:get("tod","voicednd","ringing")if(o==nil)then
return
end
get_all_profiles(r)for t,e in pairs(r)do
n[e]=false
end
local d=e:get("tod","global","enabled")local a=e:get("tod","voicednd","enabled")if(d=="0"or a=="0")then
for e,n in pairs(n)do
update_current_state(e,"off")end
return
end
local d=0
local a=0
e:foreach("tod","action",function(e)if(e.object:match("^voicednd%.(.*)$"))then
d=d+1
if(#e.timers==1 and i("",e.timers)==true)then
a=a+1
end
end
end)if(d==a)then
for e,n in pairs(n)do
update_current_state(e,"off")end
return
end
scan_for_profile_with_schedule(t,l)if(#t<1)and(#l<1)then
return
end
if(t~=nil)and(#t>0)then
if(i("All",t)==true)then
for t,e in pairs(r)do
update_current_state(e,c[o])n[e]=true
end
return
else
for t,e in ipairs(t)do
if(n[e]==false)then
update_current_state(e,c[o])n[e]=true
end
end
end
end
for t,d in pairs(n)do
if(n[t]==false)then
update_current_state(t,o)n[t]=true
end
end
e:unload("tod")e:unload("mmpbx")end
local n=e:get("tod","global","time_change_monfreq")local t=e:get("tod","voicednd","timerandactionmodified")if(t=="1")then
os.execute("sleep "..tonumber(n))e:set("tod","voicednd","timerandactionmodified","0")e:commit("tod")e:unload("tod")end
notify_new_state()