#!/bin/sh
#set -x

#-----------------------------------------------------
#
# Tomcat nohup log
#   -  3 days ago files archive
#   -  5 days ago file move process
#   - 90 days ago file delete process
#
#-----------------------------------------------------

#######################################################
# Define Constants
#######################################################
today=`date +%d`

# - Date
archiveLogYear=`date --date '3 days ago' +%Y`
archiveLogMonth=`date --date '3 days ago' +%m`
archiveLogDay=`date --date '3 days ago' +%d`

backupLogYear=`date --date '5 days ago' +%Y`
backupLogMonth=`date --date '5 days ago' +%m`
backupLogDay=`date --date '5 days ago' +%d`

makeLogYearMonth=`date +%Y%m`
removeLogYearMonth=`date --date '6 months ago' +%Y%m`


# - Dir & File
srcLogDir=/box/java_logs
logBackupDir=/box/log_backup

findArchiveFileExt=${archiveLogYear}-${archiveLogMonth}-${archiveLogDay}
findBackupFileExt=${backupLogYear}-${backupLogMonth}-${backupLogDay}


echo "today : ${today}"
echo "logBackupDir       : ${logBackupDir}"
echo "makeLogYearMonth   : ${makeLogYearMonth}"
echo "removeLogYearMonth : ${removeLogYearMonth}"
echo "findArchiveFileExt : ${findArchiveFileExt}"
echo "findBackupFileExt  : ${findBackupFileExt}"


if [ x01 == x${today} ]; then
    ###########################################
    # Check Backup Logging Directory
    ###########################################
    if [ -d ${logBackupDir}/${makeLogYearMonth} ]; then
      echo """"
    else
      mkdir -p ${logBackupDir}/${makeLogYearMonth}
    fi

    ###########################################
    # Check Delete Backup Logging Directory
    ###########################################
    if [ -d ${logBackupDir}/${removeLogYearMonth} ]; then
        echo "remove"
        rm -rf  ${logBackupDir}/${removeLogYearMonth}
    fi
fi



#######################################################
# ${archiveLogDate} days ago Tomcat nohup log Archive Process
#######################################################
if [ x0 == x`find ${srcLogDir} -name "*${findArchiveFileExt}" | wc -l` ]; then
    echo ""
else
    # old config
    #find ${srcLogDir} -name "*${findArchiveFileExt}" | xargs -t -i mv {} ${backupLogYear}${backupLogMonth}/
    echo "gzip -f `find ${srcLogDir} -name "*${findArchiveFileExt}"`"
    gzip -f `find ${srcLogDir} -name "*${findArchiveFileExt}"`
fi

###########################################################################
# ${backupLogDate} days ago Tomcat nohup log backup Directory Move Process
###########################################################################

echo "find ${srcLogDir} -name *${findBackupFileExt}.gz"
find ${srcLogDir} -name "*${findBackupFileExt}.gz" -type f | sort | while read FNAME
do
    echo "${FNAME} ${logBackupDir}/${backupLogYear}${backupLogMonth}"
    mv ${FNAME} ${logBackupDir}/${backupLogYear}${backupLogMonth}
done
