#!/bin/bash

# check number of args
if [ "$#" -ne 4 ]; then 
  exit 1
fi

# set variables
errors=0
exfile=$1
nc=$2
minrate=$3
maxrate=$4
bindir="/usr/bin"

$bindir/icepic_root

waitall() {
  while :; do
    for pid in "$@"; do
      shift
      # check if process is still running
      if kill -0 "$pid" 2>/dev/null; then
        set -- "$@" "$pid"
      elif ! wait "$pid"; then
        ((++errors))
      fi
    done
    (("$#" > 0)) || break
  done
}

# check for valid inputs
if [[ -n $ICEROOT && -d $ICEROOT ]] && [[ -f $exfile ]] && (( $nc > 0 )) && (( $minrate > 0 )) && (( $maxrate > $minrate )); then 
  # init process id var
  pids=""
  flgs="SWAMP|PASS=500|MINRATE=$minrate|MAXRATE=$maxrate"
  # loop through and launch processes
  for ((dn=0;dn<$nc;dn++))
  do
    $exfile pic $dn health $flgs &
    pids="$pids $!"
  done
  waitall $pids
fi
# return number of errors
exit $errors

