#!/bin/bash


touser() {
    echo  -e "${@}\r"
}

SUDO=''
if (( $EUID != 0 )); then
    SUDO='sudo'
fi

if [ -e /dev/ilid ]; then
    if [ 0$(/usr/bin/getchannels -d 2>&1 | grep -iv "TRUNK" | wc -l) -gt 2 ]; then
        touser "modules already loaded and plugged"
        exit 0
    fi
fi

lm() {
    module=$1
    shift
    modcount=$(lsmod|grep "^${module} "|wc -l)
    if [ $modcount = 0 ]; then
        if ! ${SUDO} modprobe ${module} $@ 2>/dev/null >/dev/null; then
            if [ -e ${kmoddir}/${module}.ko ] ; then
                if test "$kmoddir" = "" ; then
                    kmoddir=/lib/modules/$(uname -r)/kernel/drivers/ferrari
                fi

                if ! insmod ${kmoddir}/${module}.ko $@ ; then
                    touser "start: cannot load ${module}.ko from ${kmoddir}"
                    logger -t start "cannot load ${module}.ko from ${kmoddir}"
                    return
                fi
            else
                if [ -e bin/${module}.ko ] ; then
                    if ! insmod bin/${module}.ko $@ ; then
                       touser "start: cannot load ${module}.ko from bin"
                       logger -t start "cannot load ${module}.ko from bin"
                       return
                    fi
                 #else
                    #touser "start: cannot load ${module}"
                    #logger -t start "cannot load ${module}"
                 fi
             fi
        fi
    else
        #touser "start: ${module} already loaded"
        return
    fi
    #touser "start: loaded ${module} $@"
}

getDevicePar () {
    i2cdetect -a -y ${1} ${2} ${2} | grep -q '\-\-'
    rc=$?
    if [ $rc -eq 1 ]; then
	
	if [ ${3} ]; then
	    let offset=(${3}*32)+2
	else
	    let offset=2
	fi

        TT=$(printf "%02x" $(i2cutil -y -r ${1} ${2} ${offset} b))

        if [ ${TT} = '02' -a ${T1} = 'true' ] ; then
            rc='3'
        elif [ ${TT} = '02' -a ${T1} = 'false' ] ; then
            rc='2'
        elif [ ${TT} = '03' -a ${T1} = 'true' ] ; then
            rc='3'
        elif [ ${TT} = '03' -a ${T1} = 'false' ] ; then
            rc='2'
        elif [ ${TT} = '04' -a ${T1} = 'true' ] ; then
            rc='3'
        elif [ ${TT} = '04' -a ${T1} = 'false' ] ; then
            rc='2'
        elif [ ${TT} = '05' ] ; then
            rc='4'
        elif [ ${TT} = '06' ] ; then
            rc='5'
        elif [ ${TT} = '07' ] ; then
            rc='9'
        else
            rc='4'
        fi

        unset x1Licensed

        e1Licensed=$(licinfo -t bool -M 62 -n Enable)
        if  [ "${e1Licensed}" == "TRUE" ]; then
            export e1Licensed=1
            export x1Licensed=1
        else
            unset e1Licensed
        fi

        t1Licensed=$(licinfo -t bool -M 63 -n Enable)
        if  [ "${t1Licensed}" == "TRUE" ]; then
            export t1Licensed=1
            export x1Licensed=1
        else
            unset t1Licensed
        fi
        

        tmprc="$rc"

        if [ "${rc}" == "2" -a "${x1Licensed}" == "1" -a "${e1Licensed}" != "1" ]; then
            rc='0'
        fi

        if [ "${rc}" == "3" -a "${x1Licensed}" == "1" -a "${t1Licensed}" != "1" ]; then
            rc='0'
        fi

        export i2crdserial=$(printf "%d" $(i2cutil -y -r ${1} ${2} 8 bl))
        export i2crdhwserial=$(printf "%d" $(i2cutil -y -r ${1} ${2} 12 bl))
        export i2crdrevision=$(printf "%x" $(i2cutil -y -r ${1} ${2} 7 b))

        i2crdarticle=$(i2cutil -y -r ${1} ${2} 16 bl)
        if [ "${i2crdarticle}" = "0xffffffff" ] ; then
            export i2crdarticle=0
        else
            export i2crdarticle=$(printf "%d" ${i2crdarticle})
        fi

        #echo "TT=$TT T1=$T1 tmprc=$tmprc rc=$rc e1Licensed=${e1Licensed} t1Licensed=${t1Licensed} x1Licensed=${x1Licensed} i2crdserial=$i2crdserial i2crdhwserial=$i2crdhwserial i2crdrevision=$i2crdrevision i2crdarticle=$i2crdarticle"

    fi
}

. /tmp/cmdline

if which realpath >/dev/null 2>&1; then
    self=$(realpath $0)
    if test ${self#/} = $self ; then
        self=`/opt/ferrari/tools/bin/realpath `pwd`/$self`
    fi
    here=$(dirname $self)
else
    here=$(pwd)
fi
if test $DEBUG ; then echo "$0: running from $here"; fi

. /usr/fb/debugvalues

cd ${here}


lm cfgspc

if [ "$CHIP" = "TDM" ] ; then
    if test -f /data/config.lua ; then
        if test $(grep bool_IsdnT1 /data/config.lua | grep -c true) -ge 1; then
            T1="true"
        else
            if [ "$ISDN_T1" = "1" ] ; then
                T1="true"
            else
                T1="false"
            fi
        fi
    else
        if [ "$ISDN_T1" = "1" ] ; then
            T1="true"
        else
            T1="false"
        fi
    fi

    ${SUDO} modprobe i2c-dev 2>/dev/null >/dev/null
    ${SUDO} modprobe tdm_dma 2>/dev/null >/dev/null
    sleep 1

    let i=1
    for BUS in ${I2CBUS};do
        BUS2=$(echo ${ILIDBUS} | cut -d " " -f $i)
        CONFIGBUS=$(echo ${I2CCONFIGBUS} | cut -d " " -f $i)

        XBUS="a"
        OFFSET=0
        case ${BUS2} in
            0)
                XBUS="a"
                OFFSET=0
                ;;
            1)
                XBUS="b"
                OFFSET=100
                ;;
            2)
                XBUS="c"
                OFFSET=200
                ;;
            3)
                XBUS="d"
                OFFSET=300
                ;;
            4)
                XBUS="e"
                OFFSET=400
                ;;
            5)
                XBUS="f"
                OFFSET=500
                ;;
            6)
                XBUS="g"
                OFFSET=600
                ;;
            7)
                XBUS="h"
                OFFSET=700
                ;;
        esac

        ln=$(licinfo -t string -M 46 -n HWSernum)
        if  [ "x${ln}" = "x" ]; then
            ln="unlicensed"
        fi

        hwserial=$(printf "%d " $(i2cutil -y -r ${CONFIGBUS} ${I2CCONFIGADDRESS} 12 bl))

        echo ${ln} | grep -q ${hwserial}
        retcode=$?

        if  [ ! "${BOWL}" = "1" ]; then
            retcode=0
        fi

        #Trust the customer accept all HW for now
        retcode=0
        
        if  [ "${retcode}" = "0" ]; then
	    i2cdetect -a -y ${CONFIGBUS} ${I2CCONFIGADDRESS} ${I2CCONFIGADDRESS} | grep -q '\-\-'
            if [ $? -eq 1 ]; then
                ismgb=$(lspci -n | grep -c "1011:f002")
                t=$(printf "%08x" $(i2cutil -y -r ${CONFIGBUS} ${I2CCONFIGADDRESS} 0 bl))
                HWTYPE=${t:0:4}
                BOARDTYPE=${t:2:2}
                TT=${t:4:4}
                TYPE=${t:4:2}
                SUBTYPE=${t:6:2}
                
                if [ ${TYPE} = '04' -a ${ismgb} = '1' ] ; then #thats a device eeprom maybe SMBUS missing --> check for MGB
                    t="00000302"
                    HWTYPE=${t:0:4}
                    BOARDTYPE=${t:2:2}
                    TT=${t:4:4}
                    TYPE=${t:4:2}
                    SUBTYPE=${t:6:2}
                fi

                if [ ${HWTYPE} = '0001' ] ; then
                    ADDRESSLIST="0x40 0x40 0x50 0x58"
		    declare -A OFFSETS=( [1]=0 [2]=0 [3]=0 [4]=0 )
		    declare -A TDMBUS=( [1]=1 [2]=3 [3]=5 [4]=7 )
                elif [ ${HWTYPE} = '0002' ] ; then
                    ADDRESSLIST="0x50 0x50 0x50"
		    declare -A OFFSETS=( [1]=3 [2]=1 [3]=2 )
		    declare -A TDMBUS=( [1]=3 [2]=1 [3]=2 )
                else
                    ADDRESSLIST="0x40 0x48 0x50 0x58"
		    declare -A OFFSETS=( [1]=0 [2]=0 [3]=0 [4]=0 )
		    declare -A TDMBUS=( [1]=1 [2]=3 [3]=5 [4]=7 )
                fi

                let count=1
                for ADDRESS in ${ADDRESSLIST};do
                    getDevicePar ${BUS} ${ADDRESS} ${OFFSETS[${count}]}
                    if [ "${rc}" != "0" ]; then
                        NAME=$(articletoname ${i2crdarticle}) 
                        echo "echo \"set ${TDMBUS[${count}]} ${rc} ${i2crdserial} ${i2crdarticle} ${NAME}\" | confTool /dev/ilid 0.${XBUS}/X" >>/tmp/sequence
                        echo "set ${TDMBUS[${count}]} ${rc} ${i2crdserial} ${i2crdarticle} ${NAME}" | confTool /dev/ilid 0.${XBUS}/X >/dev/null 2>/dev/null

                        if [ "${HWTYPE}" = "QUADE1" ] ; then
                            fpgaversion=$(echo fpga_version | confTool /dev/ilid 0.${XBUS}/X| head -1| cut -f 3 -d ' ')
                            echo "fpgaversion=${fpgaversion}" >>/tmp/sequence
                            if [ "${fpgaversion}" = "0106" ]; then
                                if [ "${i2crdrevision}" = "a2" ]; then
                                    echo "echo \"gpio 1 1\" | confTool /dev/ilid 0.${XBUS}/X" >>/tmp/sequence
                                    echo "gpio 1 1" | confTool /dev/ilid 0.${XBUS}/X >/dev/null 2>/dev/null
                                else
                                    echo "echo \"gpio 1 0\" | confTool /dev/ilid 0.${XBUS}/X" >>/tmp/sequence
                                    echo "gpio 1 0" | confTool /dev/ilid 0.${XBUS}/X >/dev/null 2>/dev/null
                                fi
                            fi
                        fi
                    fi
                    let count=$(($count + 1))
                done
            fi

            prio=$(calcclockprio)
            echo "clk_master ${prio}" | confTool /dev/ilid 0.${XBUS}/X
            echo "set clock master ${prio}"

            t1=$(i2cutil -y -r ${CONFIGBUS} ${I2CCONFIGADDRESS} 0 bl)
            t2=$(printf "%08x" ${t1})
            type=${t2:4:4}
            if [ "${type}" = "0201" -o "${type}" = "0203" ]; then
                relais -d /dev/i2c-${I2CBUS} -l 1 # no loop and TE mode
            fi
        else
            echo "don't plug ${hwserial} because it isn't licensed"
        fi

        let i=$i+1
    done
elif [ "${HWTYPE}" = "PCM" ] ; then
        echo "Loop only"
else
    lm ilid26 debug=$DBGilid26

    if [ -z ${S2M} ]; then
        lm hfc-4s8s debug=$DBGhfc4s8s
        NAME=$(articletoname ${i2crdarticle}) 
        for c in a b c d;do
            #echo "meta /dev/ilid  1.${c}/D $(i2crdserial) $(i2crdarticle) ${NAME}"
            meta /dev/ilid  1.${c}/D "$(i2crdserial)" "$(i2crdarticle)" "${NAME}" 2>/dev/null >/dev/null
        done
    else
        # S2M
        lm falc56 debug=$DBGfalc56
        lm tdmdsp debug=$DBGtdmdsp
        NAME=$(articletoname ${i2crdarticle}) 
        for c in a b;do
            #echo "meta /dev/ilid  1.${c}/D $(i2crdserial) $(i2crdarticle) ${NAME}"
            meta /dev/ilid  1.${c}/D "$(i2crdserial)" "$(i2crdarticle)" "${NAME}" 2>/dev/null >/dev/null
        done
    fi
fi


if ! omgversion --dot --filter="omg2.version=" | grep -q -E "=(4.2|5.0)"; then
    if test -f /data/config.lua ; then
        let routeMode=$(($(/usr/bin/omgconfiginfo --json | iconv -f iso-8859-1 -t utf-8 | jq -r ".struct_Box.string_RouteMode")))
        if [ ${routeMode} -ne 2 ]; then
            let interfaces=$(($(grep ushort_IsdnPcmPairs /data/config.lua | cut -d "=" -f 2 | cut -d "," -f 1)))
            if test ${interfaces} -ge 1; then
                ${SUDO} modprobe ilidloop selftimed=1 interfaces=${interfaces} ${ILIDLOOPPAR}
            elif ! grep -q "ushort_IsdnPcmPairs" /data/config.lua; then
                loop=$(licinfo -t bool -M 55 -n Disable)
                if  [ "${loop}" != "TRUE" ]; then
                    loop=$(licinfo -t bool -M 54 -n Enable)
                    if  [  "${loop}" != "FALSE" ]; then
                        if  [ "${BOWL}" = "1" ]; then
                            lines=$(licinfo -t int -M 55 -n MaxLines)
                            if [ ! -z ${lines} ] ; then
                                let interfaces=(${lines}+29)/30;

                                if  [ "${interfaces}" != "0" ]; then
                                    ${SUDO} modprobe ilidloop selftimed=1 interfaces=${interfaces} ${ILIDLOOPPAR}
                                fi
                            fi
                        else
                            ${SUDO} modprobe ilidloop selftimed=1 ${ILIDLOOPPAR}
                        fi
                    fi
                fi
            fi
        fi
    fi
fi

lm ilidmdm debug=$DBGilidmdm

isSingleUnit=0
if [ "$HWTYPE" = "SingleUnit1S0" -o "$HWTYPE" = "SingleUnit4S0" ]; then
    isSingleUnit=1

    if [ "${L1ACTIVE}" = "1" ]; then
        echo activate L1
        for i in a b c d;do
            checkl1 /dev/ilid 1.${i}/D 1
        done
    fi
fi

if [ "${NOLEDFLASH}" != "1" -a "$isSingleUnit" = "1" ]; then
    if which ledflash >/dev/null 2>&1; then
        ledflash 7
    fi
fi

if which setmgbtermination >/dev/null 2>&1; then
    setmgbtermination
fi

if which omgsetdisableds0tontmode >/dev/null 2>&1; then
    omgsetdisableds0tontmode
fi

if [ -e /dev/ilid ]; then
    if [ 0$(/usr/bin/getchannels -d | grep -iv "TRUNK" | wc -l) -gt 1 ]; then
        touser "modules already loaded"
        exit 0
    fi
fi

for i in $(getchannels -d 2>&1 | grep 4xS0XHFC); do 
    checkl1 /dev/ilid ${i} n
done

if [ "$HWTYPE" = "AtomBox" ]; then
    if [ ! -f /tmp/noled ] ;then echo "led 0 1832000" | tee /tmp/led | /usr/bin/confTool /dev/ilid 0.a/X >/dev/null 2>&1; fi
fi

exit 0
