#!/bin/bash

# Part of the cosima cluster
# Clean the dcosima directory on ALL remote machines

# Return:
# Positive: number of available simulation slots


commandhelp() {
  echo ""
  echo "dcosima-clean - clean a run from the dcosima directory on the remote machines";
  echo "Copyright by Andreas Zoglauer"
  echo ""
  echo "Usage: dcosima-clean [options]";
  echo ""
  echo "Options:"
  echo "  --name=[run name]: Name of the run whose directory we shuld remove."
  echo "                     Used dcosima-showdiskspace to see all runs with not cleaned directories"
  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
REMOTEDIR="DCOSIMA_!!!!_IDONOTEXIST"

# Overwrite default options with user options:
for C in "${CMD[@]}"; do
  if [[ ${C} == *-n*=* ]]; then
    REMOTEDIR=`echo ${C} | awk -F"=" '{ print $2 }'`
  elif [[ ${C} == *-h* ]]; then
    echo ""
    commandhelp
    exit 0
  else
    echo ""
    echo "ERROR: Unknown command line option: ${C}"
    echo "       See \"dcosima-clean --help\" for a list of options"
    exit 1
  fi
done

if [[ ${REMOTEDIR} == "DCOSIMA_!!!!_IDONOTEXIST" ]]; then
  echo "ERROR: You need to give a dcosima run name"
  exit 1
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

# Start with cleaning
echo " "
echo "Cleaning..."
for (( m=0; m<=$(( ${#MACHINES[*]} -1 )); m++ )); do
  REMOTECOMMAND='COUNT=`grep -c ^directory ~/.dcosima.cfg`; if [ ${COUNT} -eq 1 ]; then grep ^directory ~/.dcosima.cfg; fi;'
  REMOTEMASTERDIR=$(ssh -i ${HOME}/.ssh/dmegalib_rsa -p ${REMOTEPORT[$m]} ${REMOTEUSER[$m]}@${REMOTEHOST[$m]} 'bash -s' <<< ${REMOTECOMMAND} )
  if [ "$?" != "0" ]; then
    echo "ERROR: Failed to read remote master directory"
    continue
  fi
  REMOTEMASTERDIR=`echo ${REMOTEMASTERDIR} | awk '{ print $2 }'`
  if [ "${REMOTEMASTERDIR}" == "" ]; then
    echo "ERROR: Failed to read remote master directory"
    continue
  fi
 
  
  # Let's first retrieve a list of all directories
  REMOTECOMMAND='cd $(grep ^directory ~/.dcosima.cfg | tr -s " " | cut -d " " -f2); ls -dtr */;'
  DIRECTORIES=$(ssh -i ${HOME}/.ssh/dmegalib_rsa -p ${REMOTEPORT[$m]} ${REMOTEUSER[$m]}@${REMOTEHOST[$m]} 'bash -s' <<< ${REMOTECOMMAND} )
  if [ "$?" != "0" ]; then
    echo "ERROR: Unable to retrieve the directories!"
    continue
  fi
  
  # Check if the one we want exits and conforms to our standard (BlaBla_IDXXXXX)
  CLEANED="NO"
  for D in ${DIRECTORIES}; do
    D=${D%%/}
    if [[ ${D} == *_ID* ]] && [[ ${D} == ${REMOTEDIR} ]]; then
      # If yes, we remove it
      echo " * Cleaning ${REMOTEMASTERDIR}/${D} on ${REMOTEUSER[$m]}@${REMOTEHOST[$m]}..."
      ssh -i ${HOME}/.ssh/dmegalib_rsa -p ${REMOTEPORT[$m]} ${REMOTEUSER[$m]}@${REMOTEHOST[$m]} "if [[ -d ${REMOTEMASTERDIR} ]]; then rm -rf ${REMOTEMASTERDIR}/${D}; fi; exit 0;"
      CLEANED="YES"
      break
    fi
  done
  
  if [[ ${CLEANED} == NO ]]; then
    echo " * Nothing to clean on ${REMOTEUSER[$m]}@${REMOTEHOST[$m]}..."  
  fi
  
done

echo " "

exit 0
