#!/bin/bash

#
# This is /etc/logrotate.eos, EOS version of logrotate that extends
# logrotate to do few more things. Replace /etc/cron.daily/logrotate
# with this one during init
#

LOGROTATE_PID_FILE="/var/run/logrotate.pid"
LOGROTATE_LOCK_FILE="/var/run/logrotate.lock"
LOGROTATE_LOG_FILE="/var/log/logrot.log"
LOGROTATE_DISABLE_FILE="/var/run/logrotate.disable"

test -e $LOGROTATE_DISABLE_FILE && exit 1

touch $LOGROTATE_LOCK_FILE
lockFd=102

exit_script()
{
   # another logrotate is running
   read logrotate_pid which_logrotate < $LOGROTATE_PID_FILE
   
   if [ -e /proc/${logrotate_pid} ]; then
      if [ $which_logrotate == $BASH_SOURCE ]; then
         /usr/bin/logger -t logrotate "another logrotate (pid=$logrotate_pid) is running"
      fi
   fi
   exit 0
}

eval "exec ${lockFd}> ${LOGROTATE_LOCK_FILE}"

flock -e -n ${lockFd} || exit_script

echo $$ $BASH_SOURCE >${LOGROTATE_PID_FILE}

# cleanup 0 byte logs and cores. keep 1st and last cores.
# for 0 byte agent logs, keep last one
/etc/pre_logrotate_cleanup.sh

# Delete the log file first so that FetchLogs knows when a new file
# has been written.  Bash ">" redirect reuses the same inode, so this forces
# FetchLogs to fetch the new file contents.
oldFile="${LOGROTATE_LOG_FILE}.old"
test -f "${LOGROTATE_LOG_FILE}" && mv "${LOGROTATE_LOG_FILE}" "${oldFile}"
date > "${LOGROTATE_LOG_FILE}"
rm -f "${oldFile}"
/usr/sbin/logrotate -v /etc/logrotate.conf >> "${LOGROTATE_LOG_FILE}" 2>&1
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
      if [ ! -e /var/log/logrotatefail ];
      then
          # Save disk stats
          df >> /var/log/logrot.log 2>/dev/null
          ls -laR /var/core /var/log >> /var/log/logrot.log 2>/dev/null
          cat /var/lib/logrotate/logrotate.status >> /var/log/logrot.log
          mv /var/log/logrot.log /var/log/logrotatefail 
      fi
      /usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
fi

flock -u ${lockFd}
exit $EXITVALUE

