#!/bin/bash

# Part of the MEGAlib analysis cluster
# Check how many tasks can be run on the machine

# Return:
# Positive: number of available simulation slots


commandhelp() {
  echo ""
  echo "dmegalib-allowedinstances - check how many analysis instances can be run";
  echo "Copyright by Andreas Zoglauer"
  echo ""
  echo "Usage: dmegalib-allowedinstances [options]";
  echo ""
  echo "Options:"
  echo "  --remote=[remote machine in format omny@128.32.13.12:21022]: If given check the remote machine, if not the local"
  echo "  --help: Show this help."
  echo ""
  echo "";
  echo "Example: "
  echo "  dmegalib-allowedinstances --remote=omny@128.32.13.12:2102";
  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:
REMOTEUSER=""
REMOTEHOST=""
REMOTEPORT=""

# Overwrite default options with user options:
for C in "${CMD[@]}"; do
  if [[ ${C} == *-r*=* ]]; then
    REMOTE=`echo ${C} | awk -F"=" '{ print $2 }'`
    REMOTEUSER=`echo ${C} | awk -F"=" '{ print $2 }'  | awk -F"@" '{ print $1 }'` 
    REMOTEHOST=`echo ${C} | awk -F"@" '{ print $2 }'  | awk -F":" '{ print $1 }'` 
    REMOTEPORT=`echo ${C} | awk -F":" '{ print $2 }'`
    #echo "User: ${REMOTEUSER}, Host: ${REMOTEHOST}, Port: ${REMOTEPORT}"
  elif [[ ${C} == *-h* ]]; then
    echo ""
    commandhelp
    exit 0
  else
    echo ""
    echo "ERROR: Unknown command line option: ${C}"
    echo "       See \"dmegalib-allowedinstances --help\" for a list of options"
    exit 1
  fi
done

# Check for restricted users
if [ "${REMOTE}" == "" ]; then
  # Get the remote inhibitors
  INHIBITORS=`if [ -f ~/.dcosima.cfg ]; then cat ~/.dcosima.cfg | grep ^inhibitors; else echo 'all'; fi;`
  # Get the remote users
  RUNNINGUSERS=`who | cut -d' ' -f1 | sort | uniq`
  
  #echo "Inhibitors: ${INHIBITORS} - Users: ${RUNNINGUSERS}"
  
  for u in ${RUNNINGUSERS}; do
    if [[ *${u}* == ${INHIBITORS} ]]; then
      echo "0"  # found user on inhibitor list ${u}"
      exit 0
    fi
  done
  
  if [[ ${INHIBITORS} == *all* ]] && [[ "${RUNNINGUSERS}" != "" ]]; then # Bug triggers also on a user name with "all" in it
    echo "0" # inhibitors = all and user list ${RUNNINGUSERS}"
    exit 0    
  fi
  
fi



# Check for time restrictions
if [[ "${REMOTE}" == "" ]]; then

  GOOD=true
  TIMES=$(if [ -f ~/.dcosima.cfg ]; then cat ~/.dcosima.cfg | grep ^time; fi;)
  #echo "${TIMES}"
  START=$(echo ${TIMES} | awk '{ print $2 }')
  STOP=$(echo ${TIMES} | awk '{ print $3 }')
  if [[ ${START} == "" || ${STOP} == "" ]]; then GOOD=false; fi
  
  STARTTIME=$(date --date="${START}" +%s 2>/dev/null)
  if [ "$?" != "0" ]; then GOOD=false; fi
  STOPTIME=$(date --date="${STOP}" +%s 2>/dev/null)
  if [ "$?" != "0" ]; then GOOD=false; fi
  NOW=$(date +%s)
  #echo "Start: ${STARTTIME}, Now: ${NOW}, Stop: ${STOPTIME}"
  
  # Ignore Saturdays and Sundays
  if [[ "$(date +%u)" == "6" || "$(date +%u)" == "7" ]]; then
    GOOD=false
  fi
  
  if [[ ${GOOD} == true ]]; then  
    if [[ ${STARTTIME} -le ${STOPTIME} ]]; then
      #echo "Start < Stop"
      if [[ ${NOW} -lt ${STARTTIME} || ${NOW} -ge ${STOPTIME} ]]; then
        #echo "Bad"
        echo "0"
        exit 0
      fi
    else
      #echo "Start > Stop"
      if [[ ${NOW} -gt ${STOPTIME} && ${NOW} -lt ${STARTTIME} ]]; then
        #echo "Bad"
        echo "0"
        exit 0
      fi
    fi
  fi
fi



# Check how many tasks are running for all users:
AllowedInstances=0
if [ "${REMOTE}" == "" ]; then
  #echo "Remote A"
  RunningInstances=$(dmegalib-runninginstances)

  Load=`cat /proc/loadavg | gawk ' { print $1 }'`
  Load=`echo "${Load} + 0.5" | bc` 
  Load=`echo ${Load} | gawk -F. ' { print $1 }'`
  Load=$(( ${Load} - ${RunningInstances} ))
  if (( ${Load} < 0 )); then Load=0; fi
  #echo "Load: ${Load}"
  
  MaximumInstances=`if [ -f ~/.dcosima.cfg ]; then cat ~/.dcosima.cfg | grep ^instances; else echo 'instances $(nproc)'; fi`
  MaximumInstances=`echo ${MaximumInstances} | awk '{ print $2 }'`
  #echo "Max: ${MaximumInstances}"
  
  if [ ${RunningInstances} -ge ${MaximumInstances} ]; then 
    AllowedInstances=0; 
  else
    AllowedInstances=$(( ${MaximumInstances} - ${RunningInstances} - ${Load} ))  
  fi
  if (( ${AllowedInstances} < 0 )); then AllowedInstances=0; fi

  #echo "Allowed: ${AllowedInstances}"    
else
  #echo "Remote B"
  AllowedInstances=`ssh -i ${HOME}/.ssh/dmegalib_rsa -p ${REMOTEPORT} ${REMOTEUSER}@${REMOTEHOST} ". .bash_local; dmegalib-allowedinstances"` 
fi

echo "${AllowedInstances}"

exit 0
