#!/bin/sh
# Run from the installed examples/ dir with a full path to this script.
# If $QPIDD is set, run a private QPIDD and use it.
# If $QPID_HOST or $QPID_PORT are set, use them to connect.

DIR=$PWD
SRC=`dirname $0 | sed 's|^\([^/].*\)|'$PWD'/\1|'`/examples

# Start private broker if QPIDD is set.
if [ -n "$QPIDD" ] ; then
    export QPID_PORT=`$QPIDD -dp0` || { echo "Cannot start $QPIDD" ; exit 1; }
    trap "$QPIDD -q" EXIT
fi

cleanup() {
    test -n "$QPIDD" &&  $QPIDD -q # Private broker
    kill %% > /dev/null 2>&1	# Leftover background jobs
}

trap cleanup EXIT

ARGS="${QPID_HOST:-localhost} $QPID_PORT"


client() { "$@" $ARGS > $1.out; }
clients() { for cmd in "$@"; do client $cmd; done; }

waitfor() { until grep -a -l "$2" $1 >/dev/null 2>&1 ; do sleep 1 ; done ; }

background() {
    pattern=$1; shift
    eval "$@ $ARGS > $1.out &"
    waitfor $1.out $pattern
}

outputs() {
    wait 2> /dev/null		# Wait for all backgroud processes to complete
    for f in "$@"; do
	{ echo "==== $f"; eval "cat $f"; } >> verify.out ;
    done
}

verify() {
    dir=$1
    func=`echo $dir | tr - _`
    cd $dir || return 1
    rm -f *.out
    { $func && diff -ac verify.out $SRC/$dir/verify.in ; } || return 1
    rm -f *.out
}

HEX="[a-fA-F0-9]"
remove_uuid() {
    sed "s/$HEX\{8\}-$HEX\{4\}-$HEX\{4\}-$HEX\{4\}-$HEX\{12\}//g" $*
}

# Scripts for each example

direct() {
    clients ./declare_queues ./direct_producer ./listener
    outputs  ./declare_queues.out ./direct_producer.out ./listener.out
}

fanout() {
    clients ./declare_queues ./fanout_producer ./listener
    outputs ./declare_queues.out ./fanout_producer.out ./listener.out
}

pub_sub() {
    background "Listening" ./topic_listener
    clients ./topic_publisher
    outputs ./topic_publisher.out "topic_listener.out | remove_uuid | sort"
}
    
request_response() {
    background "Waiting" ./server
    clients ./client
    kill %% 			# Must kill the server.
    outputs "./client.out | remove_uuid" " server.out | remove_uuid"
}

# Main
EXAMPLES=${*:-direct fanout pub-sub request-response}
for ex in $EXAMPLES ; do
    if ( verify $ex; ) then echo "PASS: $ex"; else
    echo "FAIL: $ex"; RET=1; fi
done

exit $RET

