#!/bin/sh
# vim: set ts=8 sw=4 sts=4 et ai:

#M=1
HOST=127.0.0.1

pgid=`ps -opgid -p$$ | tail -n1`
trap "pkill -g$pgid" EXIT

run_sipp() {
  sipp=`which sipp`
  echo Starting: "$sipp" "$@" >&2
  TERM=dumb "$sipp" "$@" >/dev/null 2>&1 &
  echo $!
  sleep 0.5
}
  
sipp() {
  m_arg=; test -n "$M" && m_arg="-m $M"
  run_sipp $m_arg -i 127.0.0.1 -nostdin -nd -default_behaviors bye "$@"
}


pid_charlie=`\
  sipp -s charlie -ap charlie2 -p 5072 -3pcc 127.0.0.1:5099 \
    -sf callpickup-charlie.xml $HOST`
pid_bob=`\
  sipp -p 5071 -3pcc 127.0.0.1:5099 \
    -sf callpickup-bob-waits-and-tells-charlie.xml`
pid_alice=`\
  sipp -s alice -ap alice2 -p 5070 \
    -sf callpickup-alice.xml -key tel bob $HOST`

# Check that everyone is up.
pids="$pid_bob $pid_charlie $pid_alice"
lines=`ps fax | grep -E "^[[:blank:]]*(\`echo "$pids" | sed -e 's/ /|/g'\`) "`
echo >&2
echo "Processes:" >&2
echo "$lines" >&2
if test `echo "$lines" | wc -l` -ne 3; then
    echo >&2
    echo "Killing because not everyone was up..." >&2
    kill $pids 2>/dev/null
    trap "" EXIT
    exit 1
fi

# Here we infinitely wait until we're done.
echo >&2
echo "Running until all processes are done (M=$M)..." >&2
while :; do
  done_=1
  for pid in $pids; do kill -0 $pid 2>/dev/null && done_=0 && echo ${pid}... 2>&1; done
  test $done_ -eq 1 && break
  sleep 2
done
kill -9 $pids 2>/dev/null
trap "" EXIT
