#!/bin/bash
#
# Distributed perftest.
# Runs perftest clients on multiple hosts using ssh.
# 

set -e
usage() {
cat <<EOF
usage: $0 <perftest-args> -- <client-hosts ...> [ --- <broker hosts...> ]
Client & broker hosts can also be set in env vars CLIENTS and BROKERS.

Run perftest clients on the client hosts against brokers on the broker
hosts Clients are assigned to client hosts round robin: publishers
first, then subscribers. If there are multiple brokers (for cluster
tests) clients connect to them round robin.

Broker hosts can be listed with -b in perftest-args or after ---
at the end of the arguments.

Error: $*
EOF
exit 1
}

TESTDIR=${TESTDIR:-$PWD}	# Absolute path to test exes on all hosts.

collect() { eval $COLLECT=\""\$$COLLECT $*"\"; }
NPUBS=1
NSUBS=1
COLLECT=ARGS
while test $# -gt 0; do
    case $1 in
	--publish|--subscribe|--setup|--control) usage "Don't pass perftest action flags: $1" ;;
	--npubs) collect $1 $2; NPUBS=$2; shift 2 ;;
	--nsubs) collect $1 $2; NSUBS=$2; shift 2 ;;
	-s|--summary) collect $1; QUIET=yes; shift 1 ;;
	-b|--broker) BROKERS="$BROKERS $2"; shift 2;;
	--) COLLECT=CLIENTARG; shift ;;
	---) COLLECT=BROKERARG; shift;;
	*) collect $1; shift ;;
    esac
done

CLIENTS=${CLIENTARG:-$CLIENTS}
if [ -z "$CLIENTS" ]; then usage "No client hosts listed after --"; fi
BROKERS=${BROKERARG:-$BROKERS}
if [ -z "$BROKERS" ]; then usage "No brokers specified"; fi

PERFTEST="$TESTDIR/perftest $ARGS"

CLIENTS=($CLIENTS)
BROKERS=($BROKERS)
start() {
    CLIENT=${CLIENTS[i % ${#CLIENTS[*]}]}
    BROKER=${BROKERS[i % ${#BROKERS[*]}]}
    ARGS="$* --broker $BROKER"
    cmd="ssh -n $CLIENT $PERFTEST $ARGS"
    test -z "$QUIET" && echo "Client $i: $cmd"
    $cmd &
}

$PERFTEST --setup -b ${BROKERS[0]}
for (( i=0 ; i < $NPUBS ; ++i)); do start --publish; done
for (( ; i < $NPUBS+$NSUBS ; ++i)); do start --subscribe; done
$PERFTEST --control  -b ${BROKERS[0]}
