require("rsmdict")

--The Objects that is supported by the Script
local obj_ids = {
                                       
                }
      
local profiles = {}  
local overrides = {}
           
local profilePath = "/etc/rsm/ccd/profiles/"
local profileFiles = {}

local ccd_Restartcmd = "sv restart ccd"

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_profiles()
  msg = profiles_to_msg()
  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_overrides()   
   update_overrides(cfg)
   store_overrides()
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_overrides() 
  --print("Loading pf data...")   
  --sf = command_exec("cat "..serial_conf_file)  
  serial_file = sf  
  profiles = {} 
  profileFiles = {}  
  overrides = {}  
  
  --scan profiles directory for any ccd profile files
  profileFiles = scandir(profilePath) 
  table.remove(profileFiles,1)
  table.remove(profileFiles,1)  
  
  --print("Table of filenames: ") 
  --print_table(profileFiles,0)   
  
  
  --Populate the profiles array
  if(profileFiles ~= 0) then
  
      priority_overrides = 0      
      
      for k,filename in pairs(profileFiles) do
          print("Filename: "..filename)
          xml = command_exec("cat "..profilePath .. "/" .. filename)      
          name, tmp = xml:match("<profile%s+name=\"(.-)\">%s*(.-)%s*</profile>")      
          
          --Profile Information
          if name ~= nil and tmp ~= nil then
             profiles[filename] = {}
             profiles[filename].filename = filename             
             
             --add overrides
             ovr = xml:match("<overrides>%s-(.-)%s-</overrides>") or ""                          
             --priority_overrides = 0
             if ovr ~= nil then
                 for o in ovr:gmatch("<input>%s-(.-)%s-</input>") do
                    print("Override input: "..o)
                    overrides[priority_overrides] = {}
                    overrides[priority_overrides].filename = filename 
                    overrides[priority_overrides].label = o 
                    overrides[priority_overrides].count = priority_overrides             
                                                   
                    priority_overrides = priority_overrides + 1
                 end
             end            
                              
          end        
          
                    
      end     
      
  end
  
   
              
end --function

function overrides_to_msg()
  local msg = {}
  override_ctr = 0
  
  --print("Load Message: ")
  
  
  --Load overrides information into a message
  for idx,off in pairs(overrides) do     
     override_cfg = {}
     override_cfg.objid =  RSM.RSM_TagID.TAG_CCD_OVERRIDE
     override_cfg[RSM.RSM_TagID.TAG_CCD_FILENAME] = off.filename
     override_cfg[RSM.RSM_TagID.TAG_CCD_LABEL] = off.label
     override_cfg[RSM.RSM_TagID.TAG_CCD_PRIORITY] = off.count     
                  
     msg[override_ctr] = override_cfg
     override_ctr = override_ctr+1
  end
        
  
  return msg
end

function update_overrides(cfg)
    count_overrides = 0
   for idx,obj in pairs(cfg) do      
      if obj.objid and obj.objid == RSM.RSM_TagID.TAG_CCD_OVERRIDE then                    
          if obj[RSM.RSM_TagID.TAG_CCD_FILENAME] ~= '' then
              print("Incoming Profile filename: "..obj[RSM.RSM_TagID.TAG_CCD_FILENAME])        
              
              overrides[count_overrides]={}
              sf = overrides[count_overrides]              
              if sf then
                  setoverrides(sf,obj)
              end             
              
          else--New ccd profile
              print("Error: No file name provided..")                        
                             
          end -- if serial 
                
          count_overrides = count_overrides + 1
      end -- if   
   end -- for
end --function


function setoverrides(sf,obj)
    
    if obj[RSM.RSM_TagID.TAG_CCD_LABEL] then
       sf.label = obj[RSM.RSM_TagID.TAG_CCD_LABEL]
    end 
    
    if obj[RSM.RSM_TagID.TAG_CCD_FILENAME] then
       sf.filename = obj[RSM.RSM_TagID.TAG_CCD_FILENAME]
    end     
      
         
    sf.changed = 1
    print("Profile-Changed status: " ..sf.changed)
end

function store_overrides()

  for idx,pf in pairs(overrides) do
         if pf.changed and pf.changed == 1 then
            newXML = [[
 <?xml version="1.0"?>
 <profile name="]]..pf.label..[[">
     <settings>
         <temperature>
             <ideal>]]..pf.tempideal..[[</ideal>
             <range>]]..pf.temprange..[[</range>
         </temperature>
 ]]
          if pf.deltaenable == 1 then
              newXML = newXML .. [[
         <deltacooling>
             <delta>]]..pf.deltatemp..[[</delta>
             <minimum>]]..pf.deltatempmin..[[</minimum>
         </deltacooling>
 ]]
          end
          
          newXML = newXML .. [[
     </settings>
     <inputs>
         <probes>
             <internal>
                 <analog>]]..pf.internal..[[</analog>
             </internal>
 ]]

          if pf.external ~= nil then
              newXML = newXML .. [[
             <external>
                 <analog>]]..pf.external..[[</analog>
             </external>
 ]]
          end
          
          newXML = newXML .. [[
         </probes>
 ]]
          --Rest of XML done in respective lua scripts...        
                      
            --writefile(profilePath .. "/" .. pf.filename, newXML)
            writefile("/usr/share/lua/kses/" .. pf.filename, newXML)
            
         end       
  end 

end

--Testing....

print("Testing...")

--load_profiles()
--[[print("Profiles Table: ")
print_table(profiles,0)
print("Overrides Table: ")
print_table(overrides,0)
print("Fans Table: ")
print_table(fans,0)
print("Fanoutputs Table: ")
print_table(fanoutputs,0)
print("Aircons Table: ")
print_table(aircons,0)]]--
--print("Get Config...............")
--print_table(getConfig(),0)

local testCfg = {}
local obj ={}
local obj1 ={}
local obj2 ={}

obj.objid = RSM.RSM_TagID.TAG_CCD_CFG
obj[RSM.RSM_TagID.TAG_CCD_FILENAME] = "testccd.xml"
--obj[RSM.RSM_TagID.TAG_BUS_DEVICE] = "/dev/ttyS1"
obj[RSM.RSM_TagID.TAG_CCD_LABEL] = "Testccd_change"     
--obj[RSM.RSM_TagID.TAG_BUS_TEMPLATE] = "t2s.xml"
--obj[RSM.RSM_TagID.TAG_BUS_ADDR] = "1.2.3.55"
--obj[RSM.RSM_TagID.TAG_BUS_GATE_ADDR] = "1.2.3.44"
--obj[RSM.RSM_TagID.TAG_BUS_PORT] = 88
--obj[RSM.RSM_TagID.TAG_BUS_BAUD] = "115200"
--obj[RSM.RSM_TagID.TAG_BUS_PARITY] = 1
--obj[RSM.RSM_TagID.TAG_BUS_DATA] = 5
--obj[RSM.RSM_TagID.TAG_BUS_STOP] = "1.1"
--obj[RSM.RSM_TagID.TAG_BUS_MODE] = 1

obj1.objid = RSM.RSM_TagID.TAG_BUS_SERIAL_DEV
obj1[RSM.RSM_TagID.TAG_BUS_SERIALNUM] = ""
obj1[RSM.RSM_TagID.TAG_BUS_DEVICE] = "/dev/ttyS1"
obj1[RSM.RSM_TagID.TAG_BUS_LABEL] = "TESTdlms"     
obj1[RSM.RSM_TagID.TAG_BUS_TEMPLATE] = "LandisAndGyr.xml"

obj2.objid = RSM.RSM_TagID.TAG_BUS_SERIAL_DEV
obj2[RSM.RSM_TagID.TAG_BUS_SERIALNUM] = "123"
obj2[RSM.RSM_TagID.TAG_BUS_DEVICE] = "/dev/ttyS1"
obj2[RSM.RSM_TagID.TAG_BUS_LABEL] = "TESTfldd"    

testCfg[0] = obj
--testCfg[1] = obj1

setConfig(testCfg)





























