#---------------------------------------------------------------------------
# waitfor
#
# Description:
#	Wait for a string in stdin or from a shell-command.
#	A timeout (seconds) must be specified;  if the string does not occur
#	within the timeout period, the waitfor exits with code 1.
#	Otherwise, if the string is found, waitfor exits with code 0.
#
# Author:
#	J. Behrs
#
# example1:
#	prompt> waitfor hello
#	this is a string
#	this is another string
#	hello this is me
#	prompt>
#
# example2:
#	prompt> waitfor bin "cat /etc/passwd"
#	prompt> 
#---------------------------------------------------------------------------
if [ $# = 0 ]; then
    echo "Usage: waitfor <string> <timeout> [ <shell-command> ]"
    exit 1
fi
TIME=$2
SLEEP=2
#
# shell-command processing
#
if [ $# = 3 ]; then
    whence $(echo $3 | awk '{print $1}') > /dev/null
    if [ $? -eq 0 ]; then
        FILE=/tmp/$$
        ( $3 ) | tee $FILE &
        teetail=$!
    else
        FILE=$3
    fi
    #
    # waitfor file to exist
    #
    while [ ! -f $FILE ]; do
        if [ $TIME -le 0 ]; then
            exit 1
        fi
        TIME=`expr $TIME - $SLEEP`
        sleep $SLEEP
    done
    #
    # waitfor token to appear in file
    #
    $0 "$1" $2 < $FILE
    rc=$?
    #
    # kill process group if command is a tail -f
    #
    case $3 in
        "tail"*"-f"*) ps -eF "%P %p" |\
                      awk "/^$teetail/"'{ system("kill -9 "$2) }';;
    esac
    rm -f /tmp/$$
    exit $rc
fi

while true; do
    while read a; do
        case "${a}" in
            $1*) exit 0;;
        esac
    done
    [ $TIME -le 0 ] && exit 1
    TIME=`expr $TIME - $SLEEP`
    sleep $SLEEP
done
exit 1
#
#    Version      Date     Time    Owner   Comment
# ------------- -------- -------- -------- ----------------------------
# V1.2          11/11/94 18:23:33 nrjbehrs modify med-ready/supp i-t-s
