#!/bin/bash

# Part of the cosima cluster
# Kill ALL instances of cosima on the cluster

# Return:
# N/A


commandhelp() {
  echo ""
  echo "dcosima-killall -- kill all cosima processes on the remote machines";
  echo "Copyright by Andreas Zoglauer"
  echo ""
  echo "Usage: dcosima-killall";
  echo ""
  echo "Options:"
  echo "  --help: Show this help."
  echo ""
  echo "";
  echo "Example: "
  echo "  dcosima-clean";
  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

# Default options:
CFG=~/.dcosima.cfg
MEGALIBPATH="Science/Software"

# Find the master simulation directory
MASTERDIR=( `cat ${CFG} | grep "^directory" | gawk '{ print $2 }'` )
if [[ "${MASTERDIR}" == "" ]]; then
  MASTERDIR="dcosima"
fi
if [[ ${MASTERDIR} == /* ]]; then
  echo "ERROR: The simulation directory can not be an absolute path! Using default path dcosima"
  MASTERDIR="dcosima"
fi
if [[ ${MASTERDIR} == .* ]]; then
  echo "ERROR: The simulation directory must sit in the users main directory! Using default path dcosima"
  MASTERDIR="dcosima"
fi

# 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

# Create the install paths on all machines
for (( m=0; m<=$(( ${#MACHINES[*]} -1 )); m++ )); do
  echo "Killing all cosima instances for user ${REMOTEUSER[$m]} on ${REMOTEHOST[$m]}..."
  ssh -i ${HOME}/.ssh/dmegalib_rsa -o ConnectTimeout=5 -p ${REMOTEPORT[$m]} ${REMOTEUSER[$m]}@${REMOTEHOST[$m]} "killall -u ${REMOTEUSER[$m]} cosima; exit 0;"
done


exit 0
