#!/bin/sh

#
# bbrun
#
# Sean MacGuire
# Version 1.8
# May 03rd, 2001
#
# This program is Copyright (c) 1997-2002
# BB4 technologies inc
# All Rights Reserved
#
# Execute BB shell scripts
# loop them forever
#

if test ! -x "$1"
then
	echo "Can't execute $1, exiting"
	exit 1
fi

if test "$BBSLEEP" = ""
then
	echo "BBSLEEP not set, exiting"
	exit 2
fi

# Save the pid of this bbrun for runbb.sh stop processing
echo "$$" >> $BBPID

while true
do
	START=`$BBHOME/bin/touchtime -e`
	$1
	END=`$BBHOME/bin/touchtime -e`
	BBTIME=`$EXPR $END - $START`

	if [ "$BBTIME" -lt "$BBSLEEP" ]
	then
		# Fix for invalid BBTIME
		# If xntpd/ntpdate changes date back a few
		# seconds/mins/hours may cause this
		if [ "$BBTIME" -lt 0 ]
		then
			echo "`$DATE` bbrun ($1) Runtime $BBTIME is invalid"
			BBTIME=`$EXPR 0 - $BBTIME`
			BBTIME=`$EXPR $BBTIME % $BBSLEEP`
		fi
		# echo "BBTIME is $BBTIME"
		SLEEPYTIME=`$EXPR $BBSLEEP - $BBTIME`
		# echo "SLEEPYTIME is $SLEEPYTIME"
		sleep $SLEEPYTIME
	else
		echo "`$DATE` bbrun: ($1) Runtime $BBTIME longer than Sleeptime $BBSLEEP"
	fi
done

