#!/bin/bash

if [ $1 == "-h" -o $1 == "--help" ]; then
	echo "$(basename $0) [-s|-p] ITERATIONS COMMAND"
	exit
fi

ACTION=$1
ITERATION=$2
shift 2

_term() { 
  echo "Caught SIGTERM signal!" 
  kill -TERM "$child" 2>/dev/null
  exit
}

trap _term SIGTERM SIGINT

for (( i = 0; i < ITERATION; i ++ )); do
	echo -ne "\r$i / $ITERATION"
	$@ &
	child=$! 
	wait "$child"
	RET=$?
	if [ $RET -ne 0 ]; then
		echo "FAILURE: $RET @ $i"
	fi
	if [ $ACTION == "-s" -a $RET -ne 0 ]; then
		exit $RET
	fi
done
echo -ne "\r$ITERATION / $ITERATION"

exit 0