#######################################################################
#
# Usage: waitForServerToStop ServerName DelayInSeconds
#
# Description:
#       Wait for the server to stop.
#       A timeout (seconds) must be specified.  If it doesn't stop
#       within the timeout period, we exit with code 1.
#       Otherwise, we exit with code 0.
#
# Author:
#       Kirk Kemp
#
#######################################################################
#set -x
typeset bn=$(basename $0)
if [ $# -lt 2 ]; then
    echo "Usage: waitForServerToStop <server-name> <timeout>"
    exit 1
fi
typeset ENAME=`id -un`
printf "%-16s[%3d]: \$1 = \"$1\"\n" $bn $LINENO
printf "%-16s[%3d]: \$ENAME = \"$ENAME\"\n" $bn $LINENO
if [ $(uname) = HP-UX ]; then # HP-FIX,JJB,28Aug95.
    set +xv
    count=0
    SLEEP=`expr $2 / 10` 
    while [ $count -le 10 ]; do
       present="$( ps -fu$ENAME | grep -v grep | grep '[ ]'$1 )"  
       [ "$present" = "" ] && exit 0
       sleep $SLEEP                        # Wait for server to stop.
       count=`expr $count + 1`
    done

    # Sorry, tried 10 times to stop gracefully, therefore kill below.
    set - 
else
    SLEEP=5
    TIME=$2
    sleep $TIME &
    alarm=$!
    while ps -ef | grep -v grep | grep "sleep" | grep $alarm > /dev/null; do
        if ps -fu$ENAME | grep '[ ]'$1; then
            sleep $SLEEP
            continue
        fi
        exit 0
    done 2> /dev/null
fi
#
# server didn't stop so we have to terminate it.
#
printf "%-16s[%3d]: Terminating server $1 that didn't stop.\n" $bn $LINENO
ps -fu$ENAME | grep -v grep | grep '[ ]'$1 | awk '{ print $2 }' | xargs -n1 kill -9

exit 1
#
#    Version      Date     Time    Owner   Comment
# ------------- -------- -------- -------- ----------------------------
# V             06/28/94 16:49:54 nrjbehrs Creation
# V1.2          06/29/94 11:50:56 nrjbehrs made timeout accurate
# V1.3          06/29/94 16:58:09 nrjbehrs add sleep 5
# V1.2          07/25/94 12:32:51 nrjbehrs IUT cleanup
# V1.3          08/18/94 16:26:49 nrjbehrs IUT cleanup
# V1.4          08/22/94 15:48:11 kok      updates for IUT
