#!/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)

    count=$(ps -C isdn.prc l | grep "\-\-slot=${ilidslot} \-\-slot-index=${ilidindex}" | wc -l)
    
    if [ "${count}" == "0" ]; then
      l1state=OFF;
      l2state=OFF;
      calls=0 
    elif ! exists "/tmp/L2State-$ilid-D*" ;then 
      l1state=IDLE;
      l2state=IDLE;
      calls=0 
    else
      l1state=$(checkl1 /dev/ilid $ilid/D | grep "Layer1 activated" | wc -l)
      if [ "${l1state}" == "0" ]; then
         l1state=DOWN
	 l2state=IDLE;
      else
         l1state=UP
         l2state=$(grep "MULTIPLE_FRAME_ESTABLISHED" /tmp/L2State-$ilid-D-* 2>/dev/null | wc -l)
         if [ "${l2state}" == "0" ]; then
	    l2state=IDLE;
	 else
	    l2state=ESTABLISHED;
	 fi
      fi
      calls=$(grep -E "(active|none)" /tmp/BChannelState-$ilid-B* 2>/dev/null | wc -l)
    fi
    
    echo ILID:$ilid, L1:$l1state, L2:$l2state, CALLS:$calls;
done;
