require("rsmdict")

--The Objects that is supported by the Script
local obj_ids = {
                   RSM.RSM_TagID.TAG_DATETIME_CFG                                    
                }
      
local datetime = {}  
           
local ntp_conf_path = "/etc/ntp.conf"
local ntp_logfile_path = "/var/log/ntpd.log"
local ntp_driftfile_path = "/var/ntpd/ntpd.drift"
local ntp_default_server = "ntp.is.co.za"

local ntp_start = "/usr/bin/sv up /service/ntpd"
local ntp_stop = "/usr/bin/sv down /service/ntpd"
local ntp_restart = "service ntpd restart"

local swclock_read = "date"
--local hwclock_set = "/sbin/hwclock -w -u"
local hwclock_read = "/sbin/hwclock -r -u"
local hwclock_show = "/sbin/hwclock --show -u"

local get_year = "date +%Y"
local get_month = "date +%m"
local get_day = "date +%d"
local get_hour = "date +%H"
local get_minute = "date +%M"
local get_sec = "date +%S"


local testPath = "/usr/share/lua/kses/IOlogicTest.xml"

local hwclock_set = "hwclock --systohc"

function print_table(t,p)

   for k,v in pairs(t) do
     print(p,k,v)
     if(type(v)=="table") then 
         print_table(v,p.."\t")
     end
  end
end


--Retuen the Object List
function getObjects()
 return obj_ids;
end

--Convert the config file into an object message nd return that.
--Actually supposed to check the request object to find the exact object if any to 
--return. We jippo that by always returning all of them
function getConfig(cfg)
  load_datetime()
  --print_table(datetime,0) 
  msg = datetime_to_msg() 
  print_table(msg,0) 
  return msg
end


--Function to lookup and set a specific object(s)
--and then to update the cofig file with those values
function setConfig(cfg)
   load_datetime()   
   --print_table(rules,0)
   update_datetime(cfg)
   store_datetime()
end


function command_exec(cmd)
  local f = io.popen(cmd) 
  value = f:read("*a") or "none"
  f:close()
  return value
end

function scandir(directory)
  local i, t, popen = 0, {}, io.popen
    for filename in popen('ls -a "'..directory..'"'):lines() do
        i = i + 1
        t[i] = filename
    end
    return t
end

function writefile(fileaddres,value)
  local f = io.open(fileaddres,"w+")
  f:write(value)
  f:close()
  return true
end

function load_datetime() 
  
  --Get date and time as a string
  datetime.time = command_exec("date +\"%H:%M:%S\""):match("%s*(.-)\n")
  datetime.date = command_exec("date +\"%Y-%m-%d\""):match("%s*(.-)\n")
  
  --ntp server
  ntpconfig = command_exec("cat "..ntp_conf_path) 
  datetime.ntpserver = string.match(ntpconfig,"server ([^\n]+)") or ""
  
  --Clocks
  datetime.softwareclock = command_exec(swclock_read)
  datetime.hardwareclock = command_exec(hwclock_read)
              
end --function

function datetime_to_msg()
  local msg = {}
  datetime_ctr = 0
  
  --print("Load Message: ")
  
  --Load datetime information into a message
  
     datetime_cfg = {}     
     datetime_cfg.objid =  RSM.RSM_TagID.TAG_DATETIME_CFG
     datetime_cfg[RSM.RSM_TagID.TAG_DATETIME_DATE] = datetime.date
     datetime_cfg[RSM.RSM_TagID.TAG_DATETIME_TIME] = datetime.time 
     datetime_cfg[RSM.RSM_TagID.TAG_DATETIME_SERVER] = datetime.ntpserver        
     datetime_cfg[RSM.RSM_TagID.TAG_DATETIME_CLOCK_SOFTWARE] = datetime.softwareclock           
     datetime_cfg[RSM.RSM_TagID.TAG_DATETIME_CLOCK_HARDWARE] = datetime.hardwareclock                      
        
     msg[datetime_ctr] = datetime_cfg
     datetime_ctr = datetime_ctr+1       
       
  return msg
end

function update_datetime(cfg)
    count_rules = 0
    count_inputs = 0
    count_outputs = 0    
    
   for idx,obj in pairs(cfg) do      
      if obj.objid and obj.objid == RSM.RSM_TagID.TAG_DATETIME_CFG then   --Config Tag                 
                                      
              dtf = datetime              
              if dtf then                                
                  setdatetime(dtf,obj)
              end                         
             
      end -- if cfg    
             
   end -- for
end --function


function setdatetime(sf,obj)    
    
    
    if obj[RSM.RSM_TagID.TAG_DATETIME_DATE] then
       sf.date = obj[RSM.RSM_TagID.TAG_DATETIME_DATE]      
    end 
    if obj[RSM.RSM_TagID.TAG_DATETIME_TIME] then
       sf.time = obj[RSM.RSM_TagID.TAG_DATETIME_TIME]      
    end
    if obj[RSM.RSM_TagID.TAG_DATETIME_SERVER] then
       sf.ntpserver = obj[RSM.RSM_TagID.TAG_DATETIME_SERVER]      
    end 
    if obj[RSM.RSM_TagID.TAG_DATETIME_CLOCK_SOFTWARE] then
       sf.softwareclock = obj[RSM.RSM_TagID.TAG_DATETIME_CLOCK_SOFTWARE]      
    end  
    if obj[RSM.RSM_TagID.TAG_DATETIME_CLOCK_HARDWARE] then
       sf.hardwareclock = obj[RSM.RSM_TagID.TAG_DATETIME_CLOCK_HARDWARE]      
    end    
    
    sf.changed = 1
    
end




function store_datetime()
    
    command_exec(ntp_stop)
    value = "tinker panic 0\nlogfile "..ntp_logfile_path.."\ndriftfile "..ntp_driftfile_path.."\nserver "..datetime.ntpserver.."\n"
    scf = io.open (ntp_conf_path,"w+")
    scf:write(value)
    scf:close()
    command_exec(ntp_start)
    
    command_exec([[date --set="]]..datetime.date..[[ ]]..datetime.time..[[" +"%Y-%M-%d %H:%m:%S"]])
    command_exec(hwclock_set)

end--function loop


--Testing....

--print("Testing...")

--load_datetime()
--print("datetime Table: ")
--print_table(datetime,0)

--[[print("Fanoutputs Table: ")
print_table(fanoutputs,0)
print("Aircons Table: ")
print_table(aircons,0)]]--
--print("Get Config...............")
--print_table(getConfig(),0)
--print("Rules Table: ")
--print_table(rules,0)

local testCfg = {}
local obj ={}
local obj1 ={}
local obj2 ={}
local obj3 ={}
local obj4 ={}
local obj5 ={}
local obj6 ={}

local obj7 ={}
local obj8 ={}
local obj9 ={}
local obj10 ={}
local obj11 ={}
local obj12 ={}

local obj13 ={}

obj.objid = RSM.RSM_TagID.TAG_DATETIME_CFG
obj[RSM.RSM_TagID.TAG_DATETIME_DATE] = "2015-03-21"
obj[RSM.RSM_TagID.TAG_DATETIME_TIME] = "18:00:00"
obj[RSM.RSM_TagID.TAG_DATETIME_SERVER] = "ntp.is.co.zaa"


--Add new profile
obj6.objid = RSM.RSM_TagID.TAG_CCD_CFG
obj6[RSM.RSM_TagID.TAG_CCD_FILENAME] = ""
obj6[RSM.RSM_TagID.TAG_CCD_LABEL] = "TestNewProfile"
obj6[RSM.RSM_TagID.TAG_CCD_TEMP] = 20
obj6[RSM.RSM_TagID.TAG_CCD_RANGE] = 0
obj6[RSM.RSM_TagID.TAG_CCD_INTERNAL] = "Test Internal_new"
obj6[RSM.RSM_TagID.TAG_CCD_EXTERNAL] = "Test External_new"
obj6[RSM.RSM_TagID.TAG_CCD_ACMONITOR] = "Test ACmonitor_new"
obj6[RSM.RSM_TagID.TAG_CCD_DELTA] = 0
obj6[RSM.RSM_TagID.TAG_CCD_FAN_TYPE] = 0

obj7.objid = RSM.RSM_TagID.TAG_CCD_OVERRIDE
obj7[RSM.RSM_TagID.TAG_CCD_FILENAME] = "TestNewProfile.xml"
obj7[RSM.RSM_TagID.TAG_CCD_LABEL] = "testOverrideLabel_new"

obj8.objid = RSM.RSM_TagID.TAG_CCD_FAN
obj8[RSM.RSM_TagID.TAG_CCD_FILENAME] = "TestNewProfile.xml"
obj8[RSM.RSM_TagID.TAG_CCD_PRIORITY] = 0
obj8[RSM.RSM_TagID.TAG_CCD_LABEL] = "TestFan1 Output_new"

obj9.objid = RSM.RSM_TagID.TAG_CCD_FAN
obj9[RSM.RSM_TagID.TAG_CCD_FILENAME] = "TestNewProfile.xml"
obj9[RSM.RSM_TagID.TAG_CCD_PRIORITY] = 1
obj9[RSM.RSM_TagID.TAG_CCD_LABEL] = "TestFan2 Output_new"

obj10.objid = RSM.RSM_TagID.TAG_CCD_FAN
obj10[RSM.RSM_TagID.TAG_CCD_FILENAME] = "TestNewProfile.xml"
obj10[RSM.RSM_TagID.TAG_CCD_PRIORITY] = 0
obj10[RSM.RSM_TagID.TAG_CCD_LABEL] = "TestFan1 Output2_new"

obj11.objid = RSM.RSM_TagID.TAG_CCD_AC
obj11[RSM.RSM_TagID.TAG_CCD_FILENAME] = "TestNewProfile.xml"
obj11[RSM.RSM_TagID.TAG_CCD_PRIORITY] = 1
obj11[RSM.RSM_TagID.TAG_CCD_LABEL] = "TestACOutput1_new"

obj12.objid = RSM.RSM_TagID.TAG_CCD_AC
obj12[RSM.RSM_TagID.TAG_CCD_FILENAME] = "TestNewProfile.xml"
obj12[RSM.RSM_TagID.TAG_CCD_PRIORITY] = 2
obj12[RSM.RSM_TagID.TAG_CCD_LABEL] = "TestACOutput2_new"


--testCfg[0] = obj
--testCfg[1] = obj1
--testCfg[0] = obj2
--testCfg[0] = obj3
--testCfg[0] = obj4
--testCfg[5] = obj5

--testCfg[6] = obj6
--testCfg[7] = obj7
--testCfg[8] = obj8
--testCfg[9] = obj9
--testCfg[10] = obj10
--testCfg[11] = obj11
--testCfg[12] = obj12
--testCfg[2] = obj13

--setConfig(testCfg)
--deleteConfig(testCfg)




























