#! /bin/bash
#
# author: Bill Barrett
# March 2017

# Per AIMOPS-216 every day an OPS cron job copies the file "clock_info.txt"
#  to the directory "/home/aimsds/aim_clock_incoming/".
# On some days the contents of this file are different from the previous day.
# Other days the contents are the same.
# This script checks to see if the contents of "clock_info.txt" are different
#  from the last time it was invoked. Nothing is done other than a log message
#  if the file is unchanged.
# If the file has changed and there is new information that can be added to
#  file "/aim/sds/common/input_data/sc_offset.dat", then that file is updated.

# Can user "aimpro" read "/home/aimsds/aim_clock_incoming/clock_info.txt"
# If not have user "aimsds" give it global read permissions
file_info=`ls -l /home/aimsds/aim_clock_incoming/clock_info.txt`
permissions=`echo ${file_info} | awk '{print $1}'`
if ! [[ ${permissions} =~ ^.r..r..r.+$ ]]; then
  dateTime=`date +%Y-%m-%dT%H:%M:%S`
  ssh aimsds@aimcips "chmod a+r /home/aimsds/aim_clock_incoming/clock_info.txt"
  echo "${dateTime} permissions updated for /home/aimsds/aim_clock_incoming/clock_info.txt"
fi

# Has the file changed since the last time it was read?
dateTime=`date +%Y-%m-%dT%H:%M:%S`
changes=`diff -w /home/aimsds/aim_clock_incoming/clock_info.txt /home/aimpro/aim_clock_incoming/clock_info.txt`
if [[ -z "${changes// }" ]]; then
  echo "${dateTime} ls -l => ${file_info}"
  echo "${dateTime} /home/aimsds/aim_clock_incoming/clock_info.txt has NOT changed"
  # If there are no changes to the file then there is nothing left to do
  exit 0
fi

echo "${dateTime} /home/aimsds/aim_clock_incoming/clock_info.txt has been UPDATED"
scp aimsds@aimcips:/home/aimsds/aim_clock_incoming/clock_info.txt /home/aimpro/aim_clock_incoming
scp_status=$?
if [ $scp_status == 0 ]; then
  year=`date +%Y`
  date=`date +%j`
  # Save a copy with a unique name
  cp /home/aimpro/aim_clock_incoming/clock_info.txt /home/aimpro/aim_clock_incoming/clock_info.${year}_${date}.txt
  dateTime=`date +%Y-%m-%dT%H:%M:%S`
  echo "${datetime} file saved as /home/aimpro/aim_clock_incoming/clock_info.${year}_${date}.txt"
  # If needed, update the '/aim/sds/common/input_data/sc_offset.dat' file
  /aim/sds/common/scripts/update_sc_clock_offset_file.py
else
  dateTime=`date +%Y-%m-%dT%H:%M:%S`
  echo "${datetime} FAILED: scp aimsds@aimcips:/home/aimsds/aim_clock_incoming/clock_info.txt /home/aimpro/aim_clock_incoming"
fi

