#!/bin/bash

. `dirname $0`/common.sh
cd $WDIR/scripts

DB=$1
NUMHOSTS=$2

if [ "$DB" != "griddb" ] && [ "$DB" != "mysql" ]; then 
	echo usage;
	exit
fi

if [ "$NUMHOSTS" == "" ] || [ "$NUMHOSTS" -lt "1" ] || [ "$NUMHOSTS" -gt "9" ]; then
	echo usage;
	exit;
fi

./build.sh

echo Copying source to other hosts...
rsync -avz $WDIR/ griddb1:$WDIR

if [ "$NUMHOSTS" -gt "1" ]; then 
	for x in `seq 2 $NUMHOSTS`; do 
		rsync -avz $WDIR/ app$x:$WDIR
	done
fi

./start_${DB}.sh

ssh griddb1 $WDIR/scripts/monitor.sh &
GDBMONPID=$!

for x in `seq 1 $NUMHOSTS`; do
	echo "Running on $x... "
	ssh app${x} $WDIR/scripts/run.sh ${DB} 1 &
	pids[$x]=$!
done

for pid in  "${pids[@]}"; do
	echo "waiting for $pid"
	wait $pid;
done

./stop_${DB}.sh

kill -9 $GDBMONPID
