#!/bin/sh 

# 
# Run ssh over & over again, as long as
# its reason for exiting is 0 or TIMEOUT
# 
# Use a child process to randomly kill ssh
#

v=0

scriptname=${1:-random.all}
echo $scriptname

SIGUSR1=30
SIGUSR2=31

TIMEOUT=$SIGUSR1
GOAWAY=$SIGUSR2

# Exit status when the exit
#  is caused by receipt of a TIMEOUT signal:
TIMEOUT_STATUS=`expr $TIMEOUT + 128`

iteration=0

#
# random_kick sits around sending SIGUSR1 to its process group
#  	at random times, and dies when it gets a SIGUSR2

trap  "if test $iteration -ne 0; then echo done with iteration $iteration; fi" $TIMEOUT;

random_kick $TIMEOUT 0 30 120 1800 &
kicker=$!

echo KICKER = $kicker

if test -x ./ssh ;  then
    while test -x ./ssh ;  do 
	iteration=`expr $iteration + 1`

	first=1
	trap  "if test $first -ne 1; then echo DIED iter $iteration; exit 1; fi" $GOAWAY
	trap  "if test $first -ne 1; then echo ignored TIMEOUT; fi" $TIMEOUT
	first=2

	./ssh -f ../scripts/$scriptname
	status=$?

	if test $status -ne 0; then
	   echo "Server died on iteration $iteration ... status = " $status

	   if test $status -ne $TIMEOUT_STATUS; then
	       echo "Not killed by timer ... killing everything... " > runssh.out
	       echo `date` >> runssh.out

	       kill -$GOAWAY $kicker
	       kill -$GOAWAY $kicker
	       echo awaiting $kicker
	       wait
	       exit 1
	    fi
	fi
    done
else
    echo ./ssh is not executable
fi;

exit 0

