#!/bin/sh

# File that will be run by Systemd before starting Tomcat
# This will cleanup old temp files from Tomcat and Pure.
# It will also create a backup of the Tomcat log files, and then remove them from the Tomcat log folder.
# The backup log folder will also be cleaned and any logs older than 7 days will be deleted.

NOW=$(date +"%Y%m%d%H%M%S")
# 0 indexed 8 is 7 days
REMOVE_BACKUP_LOGS=8
# Folder where the backup of the old Tomcat logs should be saved.
BACKUP_LOG_FOLDER=/data/backup/tomcat_logs

if [ -n "$CATALINA_BASE" ]; then

    echo
    echo "Cleanup tomcat temp files"
    rm -rf $CATALINA_BASE/temp/*
    rm -rf $CATALINA_BASE/work/*
    echo
    echo "------------ ($(date +\"%Y%m%d%H%M%S\")) ------------"
    echo

    # Will create a backup of the current Tomcat log files, before they are deleted.
    # If you do not want to backup old Tomcat log files, remove this section
    echo
    echo "Backup current logs, for possible inspection later"
    mkdir -p ${BACKUP_LOG_FOLDER}/${NOW}
    tar -czvf ${BACKUP_LOG_FOLDER}/${NOW}/tomcat_logs_${NOW}.tar.gz -C ${CATALINA_BASE}/logs .
    echo
    echo "------------ ($(date +\"%Y%m%d%H%M%S\")) ------------"
    echo

    # This cleans up old Tomcat log backup files.
    # If you do not want to backup old Tomcat log files, remove this section
    echo
    echo "Cleanup old backed up log files"
    find ${BACKUP_LOG_FOLDER}/ -mindepth 1 -type d -mtime +${REMOVE_BACKUP_LOGS} -exec rm -Rf {} \;
    echo
    echo "------------ ($(date +\"%Y%m%d%H%M%S\")) ------------"
    echo

    echo
    echo "Remove logs files in catalina base, so we have fresh start"
    rm -rf $CATALINA_BASE/logs/*
    echo
    echo "------------ ($(date +\"%Y%m%d%H%M%S\")) ------------"
    echo

    echo
    echo "Make sure permissions are correct for log files"
    chown tomcat:tomcat $CATALINA_BASE/logs
    echo
    echo "------------ ($(date +\"%Y%m%d%H%M%S\")) ------------"
    echo
fi

if [ -n "$PURE_DATA" ]; then
    echo
    echo "Remove transient data"
    rm -rf $PURE_DATA/perm/transient/*
    echo
    echo "------------ ($(date +\"%Y%m%d%H%M%S\")) ------------"
    echo
fi
