#!/bin/bash

# Part of the cosima cluster
# Check how many sims can be run on the machine

# Return:
# Positive: number of available simulation slots


commandhelp() {
  echo ""
  echo "dcosima-listrunning - list all running instances by run name";
  echo "Copyright by Andreas Zoglauer"
  echo ""
  echo "Usage: dcosima-listrunning [options]";
  echo ""
  echo "Options:"
  echo "  --help: Show this help."
  echo ""
  echo "";
  echo "Example: "
  echo "  dcosima-listrunning";
  echo "";
}


# Store command line as array
CMD=( "$@" )

# Check for help
for C in "${CMD[@]}"; do
  if [[ ${C} == *-h* ]]; then
    echo ""
    commandhelp
    exit 0
  fi
done

CFG=~/.dcosima.cfg

# Read configuration file and extract machines
MACHINES=( `cat ${CFG} | grep "^machine" | gawk '{ print $2 }'` )
REMOTEUSER=( )
REMOTEHOST=( )
REMOTEPORT=( )

#echo " "
#echo "Remote machines setup:"
for (( m=0; m<=$(( ${#MACHINES[*]} -1 )); m++ )); do
  REMOTEUSER[$m]=`echo "${MACHINES[$m]}" | awk -F"@" '{ print $1 }'` 
  REMOTEHOST[$m]=`echo "${MACHINES[$m]}" | awk -F"@" '{ print $2 }'  | awk -F":" '{ print $1 }'` 
  REMOTEPORT[$m]=`echo "${MACHINES[$m]}" | awk -F":" '{ print $2 }'`
  #echo " * Found remote machine: ${MACHINES[$m]} (user: ${REMOTEUSER[$m]}, address: ${REMOTEHOST[$m]}, port: ${REMOTEPORT[$m]})"
done


echo " "
echo "Gathering data... this might take a minute..."
echo " " 

declare -A MAP
for (( m=0; m<=$(( ${#MACHINES[*]} -1 )); m++ )); do
  
  # Do a quick test if the machine is available:
  REMOTENAME=`ssh -i ${HOME}/.ssh/dmegalib_rsa -q -o ConnectTimeout=5 -p ${REMOTEPORT[$m]} ${REMOTEUSER[$m]}@${REMOTEHOST[$m]} "hostname"`
  if [ "$?" != "0" ]; then
    echo " * Machine ${REMOTEHOST[$m]}, port ${REMOTEPORT[$m]}, user ${REMOTEUSER[$m]}: NOT ACCESSIBLE"
    continue
  fi  

  # Now get all Cosima instances
  REMOTECOMMAND='ps -ef | grep cosima | grep \_ID | grep -v "bash "'
  RUNNINGCOSIMAS=( $(ssh -i ${HOME}/.ssh/dmegalib_rsa -p ${REMOTEPORT[$m]} ${REMOTEUSER[$m]}@${REMOTEHOST[$m]} 'bash -s' <<< ${REMOTECOMMAND} ) )

  for ((index=0; index < ${#RUNNINGCOSIMAS[@]}; index++)); do
    if [ "${RUNNINGCOSIMAS[index]}" == "-t" ]; then
      RUN=${RUNNINGCOSIMAS[index+1]}
      if [[ ${MAP[${RUN}]} == "" ]]; then
        MAP[${RUN}]=0
      fi
      MAP[${RUN}]=$(( MAP[${RUN}] + 1 ))
    fi
  done
  
done

# Now print our map:

if [[ ${#MAP[@]} == 0 ]]; then
  echo "No running dcosima instances found"
else
  echo "dcosima runs and the number of executing cosima instances:"
  for i in "${!MAP[@]}"; do
    NAME=$i
    COUNTER=${MAP[$i]}
    echo " * ${NAME}: ${COUNTER}"
  done
fi

echo " "

exit 0
