#!/bin/bash
#
# delete_cips_from_hampton.sh
#
# Bill Barrett January 2020
#
# A script to delete superseded directories from Hampton University
# Note this requires a system that has been set up for passwordless
# ssh into the Hampton server

# Get the name of this shell script less the extension
this_program=`echo "$0" | awk -F "/" '{print $NF}'`
name_root=`echo "${this_program}" | awk -F "." '{print $1}'`

# The directory where the log files will be written
LOG_FILE_DIR=/aim/logs/cips/rsync

# The individuals who will receive the email that this script sends out
EMAIL_RECIPIENTS="wbarrett@lasp.colorado.edu,james.craft@lasp.colorado.edu"

# Create (or update) a log file using the current date
date_string=`date "+%Y_%m_%d"`
mkdir -p $LOG_FILE_DIR
logfile_name="${LOG_FILE_DIR}/${name_root}-${date_string}.log"
touch $logfile_name

# Is the script already running? During large data deletions cron may try to start a new job
#  before the previous one has finished.
this_program="${this_program%.*}"
script_count=`ps a | grep "$this_program" | grep -v grep | wc -l`
# Anything more than this instance is too much.
# Even when only one copy of the script is running 'ps a' often returns something like:
#   6849 pts/4    S+     0:00 /bin/bash ./delete_cips_from_hampton.sh
#   6859 pts/4    S+     0:00 /bin/bash ./delete_cips_from_hampton.sh
# So a count in the range [0-2] is acceptable. Anything else is not.
if [ [ $script_count -gt 2 ] ]; then
  date_string=`date "+%Y-%m-%d %H:%M"`
  echo "$date_string Exiting because $script_count copies of $this_program are already running" | \
    tee -ia $logfile_name
  exit 0
fi

ssh aim_cips@aim.hamptonu.edu "bash -s" < hampton_deletion_script.sh | tee -ia $logfile_name

# Send out an email when the script has completed
mail -s "${this_program} complete" <$logfile_name $EMAIL_RECIPIENTS

exit 0

