#!/bin/bash
#

function exists {
   for x in $*; do
     test -e "$x" && return 0;
   done
   return 1
}

c=$(getchannels -d 2>&1 > /dev/null | grep "/D")

for i in $c; do 
    ilid=$(echo $i | sed -e "s/\(.*\)\/D\/.*/\1/")
    ilidslot=$(echo ${ilid} | cut -d "." -f 1)
    ilidindex=$(echo ${ilid} | cut -d "." -f 2)

    l1state=OFF;
    l2state=OFF;
    calls=0 
    
    count=$(ps -C isdn.prc l | grep "\-\-slot=${ilidslot} \-\-slot-index=${ilidindex}" | wc -l)
    if [ "${count}" != "0" ]; then
        l1state=$(checkl1 /dev/ilid $ilid/D | grep "Layer1 activated" | wc -l)
        if [ "${l1state}" == "0" ]; then
            l1state=DOWN
        else
            l1state=UP
            if exists "/tmp/L2State-$ilid-D*" ;then 
                calls=0 
                l2state=$(grep "MULTIPLE_FRAME_ESTABLISHED" /tmp/L2State-$ilid-D-* 2>/dev/null | wc -l)
                if [ "${l2state}" == "0" ]; then
	            l2state=IDLE;
                else
	            l2state=ESTABLISHED;
                    calls=$(pgrep -lf "/usr/fb/bin/.*prc .*=${ilid}/B*" | grep -v -E "isdn.prc|readchannel.prc" | wc -l 2>/dev/null)
                fi
            fi
        fi
    fi

    echo ILID:$ilid, L1:$l1state, L2:$l2state, CALLS:$calls;
done;
