#! /bin/bash


help() {
  echo ""
  echo "mdelay - script for MEGAlib";
  echo "(C) by Andreas Zoglauer"
  echo "";
  echo "Usage:";
  echo "    mdelay [program name] [maximum number of instances]";
  echo "";
  echo "Examples:";
  echo "    mdelay cosima 4";
  echo "    mdelay \"bash myscript.sh\" 2ll";
  echo "";
  echo "This script makes sure that not more than the given number of instances"
  echo "are running on this machine."
  echo "";
}

if [ $# -ne 2 ]; then
    echo "Error: This script requires two input parameters, the program name and the maximum instances"
    exit -1;
fi

ProgramName=`echo $1 | awk -F" " '{ print $1 }'`
ProgramName=`basename ${ProgramName}`
ProgramCommands=`echo $1 | awk -F" " '{for (i=2; i<=NF; i++) print $i}'`
Program="${ProgramName} ${ProgramCommands}"
MaxRunningInstances=$2
RunningInstances=65536

while [ ${RunningInstances} -ge ${MaxRunningInstances} ]; do
  # Some tniy explanations:
  # -A prints all users,
  # -f list full command line so that program name can be something like bash mine.sh,
  # [ ] prevent the listing of the grep itself
  # We exclude this process itself in the listing
  # sed -> don't remember
  RunningInstances=`ps -Af | grep "[ ]${Program}" | grep -v "mdelay ${Program}" | grep -v "bash -c " | wc -l | sed 's/^ *//g'`
  if [ ${RunningInstances} -eq 0 ]; then
    exit 0;
  fi
  if [ ${RunningInstances} -ge ${MaxRunningInstances} ]; then
    echo "Waiting for a free slot: Running ${RunningInstances} of ${MaxRunningInstances} allowed instances of ${Program}"
    sleep 5;
  fi
done

exit 0;
