#!/bin/bash
#
# Oneshot logrotate to compress existing huge files
# This should save situation when system is crashing very fast
# (logrotate from cron job may not help in this case)
#
# Copyright (c) 2016-2017 by Cisco Systems, Inc.
# All rights reserved.
#

/usr/bin/logrotate /etc/logrotate.conf > /dev/null 2>&1
if [ "$?" != "0" ]; then
    fretta_restart_log_files="fia_driver_restart.log fib_mgr_restart.log bma_restart.log bme_restart.log l2fib_mgr_restart.log"
    for f in ${fretta_restart_log_files} ; do
        # the *.? and *.3.gz files are temp files created during logrotate, 
        # in case of logrotate failed, this files will not be removed. 
        # if *.1 file is exist, logrotate will failed again.
        # *.gz files are created by early version of this S89logrotate, 
        # it not match logrotate filename pattern, logrotate will not clean it.
        /bin/rm -rf /var/log/${f}.?
        /bin/rm -rf /var/log/${f}.3.gz 
        /bin/rm -rf /var/log/${f}.gz 
        if [ -f /var/log/${f} ] ; then
            if [ -f /var/log/${f}.1.gz ] ; then
                /bin/mv -f /var/log/${f}.1.gz /var/log/${f}.2.gz
                /usr/bin/logger "moved /var/log/${f}.1.gz to /var/log/${f}.2.gz"
            fi
            /bin/gzip -c /var/log/${f} > /tmp/${f}.1.gz
            /bin/rm -f   /var/log/${f}
            /bin/mv      /tmp/${f}.1.gz /var/log
            /usr/bin/logger "compressed /var/log/${f}"
        fi
    done
    /usr/bin/logrotate /etc/logrotate.conf > /dev/null 2>&1
fi
