#!/bin/bash
CONF=/etc/config/qpkg.conf
QPKG_NAME="ISB"
Install_Path=$(/sbin/getcfg $QPKG_NAME Install_Path -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

ARCH_DIR="";
cpu_arch=$(/bin/uname -m)
case "$cpu_arch" in
	x86_64 | AMD64 | amd64)
		QNAP_Version=$(/sbin/getcfg System Version -f  /etc/default_config/uLinux.conf 2>/dev/null)
		REGEXP="(^3\..+)|(^4\.[12]\..+)"
		if [[ $QNAP_Version =~ $REGEXP ]]; then 
			ARCH_DIR="x86/";#64 Bit erst ab 4.3.x möglich
		fi
		;;
	*)
		#x86_32 | i686 | i386
		;;
esac
#ARCH_DIR="x86/";
echo "$QNAP_Version-$cpu_arch-$ARCH_DIR"

counterMax=15
sleepMax=10;
#Nur alle counterMax wird aufwändig geprüft ob alle jobs laufen.
#Dazwischen wird immer geprüft, ob eine Neustart durch das Web-Interface ansteht

counter=1
sleep=10;
while true; do
	if test $counter -le 1; then
		isbs=`ls $base`
		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 
					startIt=1;
#echo "$isb $pgm"
					if test -f /tmp/isb_${isb}_${pgm}.pid; then
						pgmpid=$(cat /tmp/isb_${isb}_${pgm}.pid 2> /dev/null)
#echo "$isb $pgm PID: $pgmpid"
						if test $pgmpid; 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
								startIt=0;
#echo "do not start it, $pgmpid is running"
							fi
						fi
					fi;
					if test $startIt -eq 1; then
						($base/bin/${ARCH_DIR}$pgm $isb $base/ 2>&1) >   $base/$isb/${pgm}StdErrOut.txt &
						echo $! > /tmp/isb_${isb}_${pgm}.pid
echo -n "start $pgm PID: $! "; date;
					fi;
				done;
			fi;
		done
		let counter=counterMax+1;
		sleep=$sleepMax;
	fi;
	let counter=counter-1;
#echo "sleep $sleep, counter $counter";
	sleep $sleep;
	if test -e /tmp/isbLock; then
if test $sleep -ne 3; then
echo -n "lock detected "; date;
fi;
		counter=2;
		sleep=3;
	fi;
done

#(./isbWatchDog.sh 2>&1) > ../out.txt &