#!/bin/sh
. `dirname $0`/env

brokerpid() {
    netstat -tpl 2> /dev/null | awk '/amqp/ {print gensub("/.*$","","g",$7) }'
}

killbroker () {
    PID=`brokerpid`
    if [ -n "$PID" ] ; then kill $PID ; fi
    for ((i=5;i--;)) {
	if [ -z "`brokerpid`" ] ; then exit 0 ; fi
	sleep 1
    }
    echo "Broker `brokerpid` refuses to die."
}

waitbroker () {
    while [ -z `brokerpid` ] ; do sleep 1 ; done
}

startbroker() {
    case $1 in
	j)   
	    export AMQJ_LOGGING_LEVEL=fatal
	    export JDPA_OPTS=
	    export QPID_OPTS=-Xmx1024M
	    export debug=1
	    CMD="qpid-server"
	    qpid-run -run:print-command # Show the command line.
	    ;;
	c)  CMD=qpidd ;;
    esac
    nohup $CMD  > /dev/null 2>&1 &
    waitbroker
    echo Broker started: $CMD
}


case $1 in
    j|c) startbroker $1 ;;
    stop|kill) killbroker ;;
    wait) waitbroker ;;
    pid) brokerpid ;;
esac
