#! /bin/bash
#
# (C) 2000, Ingvar Mattsson, <ingvar@bofh.se>
#

TYPE=local
CONCURRENT=1
PROG=$0
LOGFILE=logs/testrun.$(date '+%Y-%H:%H:%S')
RUNS=1000

usage ()
{
  echo "$PROG: usage:"
  echo "	$PROG [-t n|l|b] [-r <run>] [-c <concurrent sessions>] [-?]"
  echo
  echo "	  -t n|l|b	Run network, local or both (local is default"
  echo "	  -c <num>	Concurrent sessions"
  echo "	  -r <runs>	Number of runs per session (defaults to 1000)"
}

run ()
{
  make test$1 > /dev/null 2>&1
  count=0
  pidacc=""
  while [ $count -lt $CONCURRENT ]
  do
    echo "DEBUG: count = $count" >> /dev/tty
    ./test$1 $4 >> $3 2>&1 &
    pidacc="$pidacc $!"
    count=$(($count + 1))
  done

  echo $pidacc
}

# Eat all them arguments!
while [ "x$*y" != xy ]
do
  case $1 in
    -t*) case $1 in	# Default giving an error?
           -tl) TYPE=local ;;
           -tn) TYPE=net ;;
           -tb) TYPE=both ;;
           -t) case $2 in	# Default giving an error?
                 b) TYPE=both ;;
                 l) TYPE=local ;;
                 n) TYPE=net ;;
               esac
               shift ;;
         esac ;;
    -c*) if [ "x$1" = "x-c" ]
         then
           CONCURRENT=$2
           shift
         else
           CONCURRENT=`echo $1 | cut -c3-`
         fi ;;
    -r*) if [ "x$1" = "x-r" ]
	 then
           RUNS=$2
           shift
         else
           RUNS=`echo $1 | cut -c3-`
         fi ;;
    '-?') usage; exit 0;;
  esac
  shift
done

echo "$CONCURRENT $TYPE tests will be run $RUNS times"

case $TYPE in
  local) pids=`run local $CONCURRENT $LOGFILE.local $RUNS` ;;
  net) pids=`run net $CONCURRENT $LOGFILE.local $RUNS` ;;
  both)  pids=`run local $CONCURRENT $LOGFILE.local $RUNS`
         pids="$pids `run net $CONCURRENT $LOGFILE.local $RUNS`" ;;
esac

# Now we should have everything up and running, mangle pids for easy grepping

echo "DEBUG: pids=$pids"

for pid in $pids
do
  manglepids="$manglepids `echo $pid | sed 's/\(.\)\(.*\)/*[\1]\2 /'`"
done

finished=nope
while [ $finished = nope ]
do
  finished=yep
  ps -u $USER > /tmp/testdrible.$$
  for pid in $manglepids
  do
    if grep -q "^ *$pid" /tmp/testdrible.$$
    then
      finished=nope
    fi
  done
  if [ $finished = nope ]
  then
    sleep 60
  fi
done
