#!/bin/sh
# Run from the installed examples/ dir with a full path to this script.
#

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

# Start private broker if QPIDD is set.

if [ -n "$QPIDD" ] ; then
    # FIXME aconway 2007-12-14: Should use --port 0, need
    # to make examples clients more flexible to connect.
    # 
    $QPIDD -d || { echo "Cannot start $QPIDD" ; exit 1; }
    trap "$QPIDD -q" EXIT
fi

# Utility functions

run() {
    echo ==== $*; eval "$*"; echo ====;
}

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

verify() {
    ex=`basename $PWD`
    diff -ac verify.out $SRC/$ex/verify.in || {
	echo "FAIL: $ex  " ; RET=1 ; return 1;
    } 
}

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() {
    run ./declare_queues  > verify.out
    run ./direct_producer >> verify.out
    run ./listener >> verify.out
}

persistent() {
    run ./declare_queues >> verify.out
    run ./direct_persistent_producer >> verify.out
    run ./listener >> verify.out
}

fanout() {
    run ./declare_queues > verify.out
    run ./fanout_producer >>verify.out
    run ./listener >>verify.out
}

pub_sub() {
    ./topic_listener | tee topic_listener.out > topic_listener.wait &
    waitfor topic_listener.wait  "Listening"
    run ./topic_publisher > verify.out
    wait 
    run remove_uuid "topic_listener.out | sort" >> verify.out
}
    
request_response() {
    ./server | tee server.out > server.wait &
    waitfor server.wait "Waiting"
    run ./client | remove_uuid > verify.out
    kill %%
    wait 2> /dev/null
    run remove_uuid server.out >> verify.out
}

# FIXME aconway 2007-12-14: put back pub-sub and persistence when fixed.

# Main
for ex in  direct fanout request-response  ; do
    func=`echo $ex | tr - _`
    echo "Verifing $ex"
    ( cd $ex && $func && verify && rm -f *.out *.wait) 
done

exit $RET

