#!/usr/bin/lua

if _VERSION == "Lua 5.0.2" then
   function printf(...)
      local s
      
      --print(_VERSION)
      
      s = string.format(unpack(arg))
      if (string.sub(s, -1, -1) == "\n") then
         s = string.sub(s, 1, -2)
      end
      print(s)
      if DOFLUSH==true then
         io.flush ()
      end
   end
else
   function printf(fmt,...)
      local s
      
      --print(_VERSION)
      
      s = fmt:format(...)
      
      if (string.sub(s, -1, -1) == "\n") then
         s = string.sub(s, 1, -2)
      end
      
     print(s)
     if DOFLUSH==true then
         io.flush ()
      end
   end
end

dataDir = os.getenv("DATA_DIR") or "/data"
dofile(dataDir .. "/config.lua")

doDebug = false

function getProtocolStringAndDirection(protocol)
    if tonumber(protocol) == 2 then
        return "PP","TE"
    elseif tonumber(protocol) == 3 then
        return "PMP","TE"
    elseif tonumber(protocol) == 6 then
        return "PPNA","TE"
    elseif tonumber(protocol) == 7 then
        return "PPNT","NT"
    elseif tonumber(protocol) == 8 then
        return "PPNTNA","NT"
    else 
        return "PMP","TE"
    end
end

if config~=nil and config.struct_Box~=nil and config.struct_Box.struct_DChannel~=nil then
    -- correct some config Settings
    if(config.struct_Box.struct_DChannel[1]==nil)then
        local t = {}
        t = config.struct_Box.struct_DChannel
        config.struct_Box.struct_DChannel = nil
        config.struct_Box.struct_DChannel = {}
        config.struct_Box.struct_DChannel[1]=t
    end

    for k,v in ipairs(config.struct_Box.struct_DChannel) do
       local protocoll,direction = getProtocolStringAndDirection(v.long_Protocol or 2)
       if doDebug then
          printf("active=%s, ilidType='%s', protocol='%s' direction='%s'\n", 
                 tostring(v.bool_CfgValid or "NIL"),
                 v.string_IlidType or "NIL",
                 protocoll or "NIL",
                 direction or "NIL"
          )
       end
       if v.string_IlidType=="S0" and v.bool_CfgValid~=true and direction=="TE" then
          string_IlidSlot = "1"
          string_IlidIndex = "a"
          string_IlidType = "S0"
          
          local cmd = "/usr/bin/checkl1 /dev/ilid " .. (v.string_IlidSlot or "NIL") .. "." .. (v.string_IlidIndex or "NIL") .. "/D/" .. (v.string_IlidType or "NIL") .. " n"
          if true then
             printf("%s\n",cmd)
          end
          os.execute(cmd)
       end 
    end
end

