#!/bin/bash
CONF=/etc/config/qpkg.conf
QPKG_NAME="ISB"
Install_Path=$(/sbin/getcfg $QPKG_NAME Install_Path -f $CONF 2>/dev/null)
isbVersion=$(/sbin/getcfg $QPKG_NAME Version -f $CONF 2>/dev/null)

base=/usr/local/TSPBUS400
if test -d /mnt/md1/bus400; then
	#IcyBox
	base=/mnt/md1/bus400
elif test -n "${Install_Path}" -a -d "${Install_Path}"; then
	base=${Install_Path}
fi
#echo $base
lsofFound=0
#Variante mit lsof ist nur 0,5s schneller bei 24 Spiegelgruppen aber ungenau, so lange Port nicht ermittelt, daher ausschalten
#if test -f /usr/sbin/lsof; then
#	lsofFound=1
#elif test -f /opt/sbin/lsof; then
#	lsofFound=1
#fi
isbs=`ls $base`
isrunningAll=1
isrunningSome=0
for isb in $isbs; do
	if test -d $base/$isb -a ! -f $base/$isb/IGNORE -a $isb != "tmp" -a $isb != "bin" -a ${isb:0:1} != "@"; then
		for pgm in tgt73c tgt74c; do
			if test -f /tmp/isb_${isb}_${pgm}.pid; then
				pgmpid=$(cat /tmp/isb_${isb}_${pgm}.pid 2> /dev/null)
				if test $pgmpid; then
					if test $lsofFound -ne 1; then
#						if test -n "$(ps ax | grep "^ *$pgmpid " | grep $isb | grep $pgm)"; then
						if test -n "$(cat /proc/$pgmpid/cmdline | tr -d '\0' | grep $isb | grep $pgm)"; then
							isrunningSome=1
						else
							isrunningAll=0
						fi
					else
						case "$($base/bin/isb.sh testConn [0-9]* $pgmpid)" in 
							LISTEN)			isrunningSome=1;;
							ESTABLISHED)	isrunningSome=1;;
							STOPPED)		isrunningAll=0;;
							*)				;;
						esac
					fi
				else
					isrunningAll=0
				fi
			else
				isrunningAll=0
			fi
		done
	fi
done
locked="";
if test -e /tmp/isbLock; then
	locked="(locked!)";
fi;
if test $isrunningAll -eq 1; then
	echo ISB v$isbVersion is started $locked;
	exit 0;
elif test $isrunningSome -eq 0; then
	echo ISB v$isbVersion is stopped $locked;
	exit 1;	
else
	echo ISB v$isbVersion is not completely started  $locked;
	exit 1;
fi;
