#!/bin/sh
set -u  # force better programming and ability to use check for not set
if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi

# sbin/$RCSfile: aml2log-stash,v $  $Revision: 1.2 $

# Usage: aml2log-stash

#node=`uname -n| sed -e 's/\([^\.]\)\..*/\1/'`
#gang=`gang`

here=`pwd`
thisYear=`date +%Y`
thisMonth=`date +%m`
thisDay=`date +%d`

LOGS=`enstore conf --show crons aml2log_dir`
if [ $? -ne 0 ]; then
   echo "Unable to obtain aml2 log directory path." > /dev/null 2>&1
   exit 1
fi
RPTS=`enstore conf --show crons aml2report_dir`
if [ $? -ne 0 ]; then
   echo "Unable to obtain aml2 report directory path." > /dev/null 2>&1
   exit 1
fi

#if [ -z "${2-}" ] ; then
#  if [ `uname -n | grep -c ${gang}srv2` -ne 0 ]; then
#    LOGS=/diska/aml2-log
#    RPTS=/diska/aml2-report
#  else
#    LOGS=/fnal/ups/prd/www_pages/enstore/aml2log
#    RPTS=/fnal/ups/prd/www_pages/enstore/aml2rpt
#  fi
#else
#  LOGS=$2
#  if [ -z "${3-}" ] ; then
#    RPTS=/junk/doesnot/exist
#  else
#    RPTS=$3
#  fi
#fi

cd $LOGS
if [ $? -eq 1 ]
then
  # The specified log directory does not exist.
  echo "AML2 log directory not accessible."  > /dev/null 2>&1
  exit 1
fi

HISTORY=history
if ! [ -d $HISTORY ]; then
   mkdir -p $HISTORY
   if [ $? -eq 1 ]; then
      echo "AML2 log history directory not accessible."  > /dev/null 2>&1
      exit 1 #The directory failed to be created.
   fi
fi

logfiles=`ls -1 log*.ascii 2>/dev/null`
for log in $logfiles; do
  last_line="`tail -n 1 $log`"
  year=` echo $last_line | cut -f1 -d-`
  month=`echo $last_line | cut -f2 -d-`
  day=`  echo $last_line | cut -f3 -d-|cut -f1 -d\ `
  stash=0
  if [ $year  -lt $thisYear  ]; then stash=1;fi
  if [ $month -lt $thisMonth ]; then stash=1;fi
  if [ $stash -eq 0 ]; then continue; fi
  mkdir -p $HISTORY/$year/$month
  # cp the file, don't mv it since another cron job will just go get it again.
  cp $log $HISTORY/$year/$month
done

cd $HISTORY
find . -type f -name "log*.ascii" -exec gzip {} \; 2>/dev/null
# if the .gz file already exists, we end up with a ascii file laying around 
#    just delete these files.
find . -type f -name "log*.ascii" -exec rm {} \; 2>/dev/null

if [ -d $RPTS ]; then
  cd $RPTS
  find . -name "*.rpt" -daystart -mtime +14 -exec rm -fr {} \;
fi

cd $here
