#!/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$  $Revision$

# Usage: log-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 log_server log_file_path`
if [ $? -ne 0 ]; then
   echo "Unable to obtain log directory path." > /dev/null 2>&1
   return 1
fi
#if [ -z "${1-}" ] ; then
#  if [ `uname -n | grep -c ${gang}srv2` -ne 0 ]; then
#    LOGS=/diska/enstore-log
#  else
#    LOGS=/fnal/ups/prd/www_pages/enstore/log
#  fi
#else
#  LOGS=$1
#fi

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

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

logfiles=`ls -1 LOG-*`
for log in $logfiles; do
  year=` echo $log | cut -f2 -d-`
  month=`echo $log | cut -f3 -d-`
  day=`  echo $log | cut -f4 -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
  mv $log $HISTORY/$year/$month
done

# also get rid of the extra log files.  these are copies
# of lines (DEBUGLOG is LOG with extra) in the LOG files, so just delete them.
for prefix in ALARM ENCPS EVRLY LMQADDS MOUNTS DEBUGLOG; do
    files=`ls -1 $prefix-* 2>/dev/null`
    for log in $files; do
      year=` echo $log | cut -f2 -d-`
      month=`echo $log | cut -f3 -d-`
      smash=0
      if [ $year  -lt $thisYear  ]; then smash=1;fi
      if [ $month -lt $thisMonth ]; then smash=1;fi
      if [ $smash -eq 1 ]; then rm $log; fi
    done
done

cd $HISTORY
#Make sure the LOG* files end in the date.
find . -type f -name "LOG-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]" -exec gzip {} \; 2>/dev/null

cd $here
