#!/usr/bin/ksh

#------------------------------------------------------------
#will pause until the needed file appears
#syntax: wait_for filename batchdir
#------------------------------------------------------------

#-----------------------------------------------
# set some defaults
#-----------------------------------------------
#--------------------------------
#set environment variables
#--------------------------------
. $WFU_PATH/global.site.ksh

filename=$1
batchdir=$2

killhours=3
let killtime=killhours*60*60
fdir=`dirname $filename`
fname=`basename $filename | tr '*' ' '`
batchlog=`echo $batchdir/batch_log`

waitfor_file=$batchdir/waiting_$$
echo $filename > $waitfor_file
echo path $fdir filename $fname >> $waitfor_file

#----------------------
#exit batch subroutine
#----------------------
exit_batch ()  {
	echo $exit_message
	rm $waitfor_file
	exit
}


#-------------------------------------------
#loop for a minute to see if we are running
#-------------------------------------------
check_running=1
while test $check_running -eq 1
	do
	runfile=`ls $fdir | grep $fname`
	len=${#runfile}
	if test $len -gt 0
		then check_running=0
		exit_message=`echo 0`
		exit_batch 
	fi
	#-----------------------
	#check for a kill file
	#-----------------------
	killfile=`ls $batchdir | grep kill`
	len=${#killfile}
	if test $len -gt 0
		then check_running=0
		exit_message=`echo 1`
		exit_batch		
	fi
	#-----------------------------------
	#check for runtime overflow and kill
	#-----------------------------------
	if test $SECONDS -gt $killtime
		then check_running=0
		message=`echo -------ERROR UNIX WAIT_FOR TIMEOUT  $filename  -----------`
		echo $message >> $batchlog
		echo 'UNIX waitfor timeout' >> $batchdir/kill
		echo $message >> $batchdir/kill
		exit_message=`echo 1`
		exit_batch
	fi
	echo $SECONDS >> $waitfor_file
	sleep $polltime
done

exit
