#!/bin/sh

# bb-ping.sh
#
# SIMPLE CONNECTIVITY TEST, TAKES AN IP ADDRESS OR NAME AS ARGUMENT
# RETURNS TEXT AND EXITS WITH AN ERROR CODE
# Sean MacGuire
# Version 1.9
# Mar 13th, 2002
#
# (c) Copyright Quest Software, Inc.  1997-2002  All rights reserved.
#

if test "$#" != "2"
then
	echo "ERROR - WRONG NUMBER OF ARGUMENTS"
	exit 1
fi

PINGHOST=$1
DIALUP=$2
STATUS="Connection OK"

TESTCOUNT="1"
if [ "$DIALUP" = "TRUE" ]
then
	TESTS=1			# ONLY TRY ONCE FOR dialup HOSTS
else
	TESTS=$PINGTESTS	# HOW MANY TIMES DO WE TEST BEFORE FAILING
fi

while test "$TESTCOUNT" -le "$TESTS"
do
	$PING $PINGPAR1 $PINGHOST $PINGPAR2 2>/dev/null | $SED 's/octet/byte/g' | $GREP -v SO_TIMESTAMP > $BBTMP/BBPING.$$ 2>&1
	bytesfrom=`$GREP "bytes from" $BBTMP/BBPING.$$ | $GREP -vi "unreachable" | $GREP -vi "exceeded" | $GREP -vi "prohibited" 2>/dev/null`
	if [ "$bytesfrom" = "" ]
	then
		SLEEPTIME=`expr $TESTCOUNT \* $PINGSLEEPFCT`
		# Don't sleep on last test
		if [  "$TESTCOUNT" -lt "$TESTS" ]
		then
			#echo "Sleeping for $SLEEPTIME @ $PINGHOST"
			sleep $SLEEPTIME
		fi
		TESTCOUNT=`expr $TESTCOUNT + 1`
		STATUS="ERROR: Can't connect to $PINGHOST"
		ERR=1
	else
		if test "$TESTCOUNT" -le "$PINGWARN"
		then
			STATUS="Connection OK"
		else
			STATUS="WARNING - Connection OK on attempt $TESTCOUNT"
		fi
		TESTCOUNT=99		# IT'S OK, WE'RE DONE
		ERR=0
	fi
done

echo "$STATUS 
`cat $BBTMP/BBPING.$$`"
$RM -f $BBTMP/BBPING.$$		# GET RID OF THE LEFTOVERS

exit $ERR
