#!/usr/bin/lua

dofile("/usr/fb/bin/sipisdn/lib.lua")

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

doDebug = false

function setTermination(type)
    byte=0
    found=false
    for k,v in ipairs(config.struct_Box.struct_DChannel) do
        if v.string_IlidType == type then
            printf("found %s %s.%s set termination %s\n", 
                   v.string_IlidType or "NIL",
                   v.string_IlidSlot or "NIL",
                   v.string_IlidIndex or "NIL",
                   tostring(v.bool_TerminationEnabled)
               )

            if v.bool_TerminationEnabled then
                if v.string_IlidIndex == "a" then
                    byte = byte + 1;
                elseif v.string_IlidIndex == "b" then
                    byte = byte + 2;
                elseif v.string_IlidIndex == "c" then
                    byte = byte + 4;
                elseif v.string_IlidIndex == "d" then
                    byte = byte + 8;
                end
            end
        end
    end

    cmd = "i2cutil -y " .. i2cbus .. " 0x08 " .. byte .. " " .. byte .. " b"
    if doDebug then
        printf("%s",cmd)
    end
    os.execute(cmd)
end

-- correct some config Settings
if config~=nil and config.struct_Box~=nil and config.struct_Box.struct_DChannel~=nil then
    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

    if os.getenv("HWTYPE") == "MGB" then
        setTermination("S0")
    end
end