#!/bin/bash

###########################################################################
#
#	Shell program to rotate log files in /var/spool and other dirs
#       anywhere on the system. Log files to be checked are to be inc-
#       luded in a seperate rc file. See docs for format of file.
#
#	Copyright 2001, USM Bish,<bish@nde.vsnl.net.in>.
#
#	This program is free software; you can redistribute it and/ or
#	modify it under the terms of the GNU General Public License as
#	published by the Free Software Foundation; either version 2 of
#	the License, or (at your option) any later version. 
#
#	This program is distributed in the hope that it will be useful
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY  or  FITNESS FOR A PARTICULAR PURPOSE. See the
#	GNU General Public License for more details.
#
#	Description: A distro-independent method of rotating log files
#       in /var/spool without necessity for cron processes.
#
#	NOTE: You must be the superuser to run this script.
#
#	Usage:
#
#		rotatelog [ -h | --help ] [-e] [-i]
#
#	Options:
#
#		-h, --help	Display this help message and exit.
#		-e              E]xecute rotation
#		-i              I]nfo on present log file sizes
#
#
#	Revisions:
#
#	Nov/03/2001	File created                    .... ver 0.1
#       Nov/04/2001     Mail to root added              .... ver 0.2
#
###########################################################################


###########################################################################
#  Editable variables
###########################################################################

#### Where to archive the old logs ?
OLDLOGS=/var/log/oldlogs

#### Where is the rotatelogrc file ?
RC=$OLDLOGS/rotatelog.rc

#### Send mail to root ? [ yes / no ]
SENDMAIL="yes"
#SENDMAIL="no"

##########################################################################
# No editing below this
##########################################################################

PROGNAME=$(basename $0)
VERSION="0.2"
TEMP_FILE1=/tmp/${PROGNAME}.$$.1
TEMP_FILE2=/tmp/${PROGNAME}.$$.2
TODAY=$(date +%y%m%d)   # YYMMDD for convenient sorting

###########################################################################
#	Functions
###########################################################################

function send_mail
{
        #### Send mail to root
        echo "#!/bin/sh" > $TEMP_FILE1
        echo "sendmail -t << -EndOfMail-" >> $TEMP_FILE1
        echo "From: rotatelog" >> $TEMP_FILE1
        echo "To: root" >> $TEMP_FILE1
        echo "Subject: rotatelog notice" >> $TEMP_FILE1
        echo "" >> $TEMP_FILE1
        date >> $TEMP_FILE1
        echo "" >> $TEMP_FILE1
        cat $TEMP_FILE2 >> $TEMP_FILE1
        echo "" >> $TEMP_FILE2
        echo "-EndOfMail-" >> $TEMP_FILE1
        chmod +x $TEMP_FILE1
        $TEMP_FILE1
        echo ""
        echo "-- Mail to root sent --"
        echo ""        
}

function chk_size
{
        CNT=0
        for i in `cat $RC | grep -v "#"`; do
           CNT=$((CNT+1))
           echo -en $CNT"]\t"
           du -b $i 
        done
}
        
function rotate_log 
{
        #### Create the backup and zip it
        BASENAME=`basename $TARGET`
        cp $TARGET $OLDLOGS/$BASENAME.$TODAY
        gzip -9 $OLDLOGS/$BASENAME.$TODAY
        echo $OLDLOGS/$BASENAME.$TODAY.gz >> $TEMP_FILE2

        #### Now zap the space occupying hogs
        cat /dev/null > $TARGET
        chmod 666 $TARGET        
}

function chk_rc
{
        if ! [ -s $RC ]; then
           echo "rc file NOT found ... "$RC
           echo -en "Create one ? [y/n] : "
           read YN
           case $YN in 
           
           Y|y) ## Create a skeleton RC file
                cat << -EndOfRC- > $RC
####################################
# Sample rotatelog.rc file.All lines 
# with # are omitted.  All filenames 
# with full path, to begin on Col 1.
# No line gaps permitted in between.
####################################
/var/log/messages                   
/var/log/syslog          
/var/log/wtmp           
/var/log/debug          
-EndOfRC-
               echo
               echo $RC" has been created"
               echo "Add to this file if more log files are to"
               echo "be included ... Press [Enter] to continue"
               echo
               read
               clear
               ;;
                
           *)  # Anything else entered
               echo "Cannot proceed without a rc file"
               term_exit
           esac
        fi                             
}

             
function chk_oldlogs
{
        if ! [ -d $OLDLOGS ]; then
           echo -en "\tFirst time run ...\n\n"
           mkdir $OLDLOGS
           chmod 755 $OLDLOGS
        fi
}           
                     
function chk_root
{
        USR=`whoami`
        if ! [ "$USR" = "root" ]; then
           echo $PROGNAME"  [Version : "$VERSION"]"
           echo "Root privileges needed ... "
           term_exit
        fi
}
           
function clean_up
{
	rm -f $TEMP_FILE1
	rm -f $TEMP_FILE2
}


function graceful_exit
{
	clean_up
	exit
}


function error_exit 
{
	echo "${PROGNAME}: ${1:-"Unknown Error"}" >&2
	clean_up
	exit 1
}

function term_exit
{
	echo "${PROGNAME}: Terminated"
	clean_up
	exit
}


function int_exit
{
	echo "${PROGNAME}: Aborted by user"
	clean_up
	exit
}


function usage
{
	echo "Usage: ${PROGNAME} [-h | --help] [-e] [-i]"
}


function helptext
{
	local tab=$(echo -en "\t\t")
		
	cat <<- -EOF-

        ${PROGNAME} ver. ${VERSION}
        	
        This is a program to rotate log files in /var/spool or
        any other directory on the system, as specified in the
        rc file : $RC
	
        $(usage)
	
        Options:
	
        -h, --help	Display this help message and exit.
        -e              E]xecute rotation
        -i              I]nfo on present log file sizes
			
        NOTE: You must be the superuser to run this script.
		
	-EOF-
}	

###########################################################################
#	Program starts here
###########################################################################

# Trap TERM, HUP, and INT signals and properly exit

trap term_exit TERM HUP
trap int_exit INT

if [ "$1" = "" ]; then
    usage
    graceful_exit
fi
       
if [ "$1" = "--help" ]; then
    helptext
    graceful_exit
fi

chk_root
chk_oldlogs
chk_rc

# Process arguments 

while getopts ":hei" opt; do
    
    case $opt in

    e )	echo
        echo $PROGNAME"     Version : "$VERSION
        echo
        chk_size
        echo
        echo "Which logs to rotate [1 - $CNT] ?"
        echo "Otherwise enter [0] ... to abort."
        echo -en "Enter numbers with with spaces in between : "
        read NOS
        
        TNOS=`echo $NOS | tr -d [:alpha:]`
        NOS=$TNOS
 
        if [ "$NOS" = "" ]; then
           echo "Invalid option"
           term_exit
        fi
         
        if [ "$NOS" = "0" ]; then
           term_exit
        fi
        
        NNNOS=`echo $NOS | awk '{print $1}'`
        if [ "$NNNOS" -gt "$CNT" ]; then
           echo
           echo "Number not in menu : "$NOS 
           term_exit
        fi          
     
        NCNT=0
        clean_up
        for i in `echo $NOS`; do
            NCNT=0
            for j in `cat $RC | grep -v "#"`; do
              NCNT=$((NCNT+1))
              if [ "$NCNT" = "$i" ]; then
                 TARGET=$j
                 echo -en "\nRotating ... $TARGET\n"
                 rotate_log
              fi
            done     
        done
        if [ "$SENDMAIL" = "yes" ]; then
           send_mail 
        fi   
        ;;
         
    i )	echo 
        echo $PROGNAME"                  Version : "$VERSION
        echo
        echo "Info on present sizes of logs in bytes :" 
        echo
        chk_size
        echo
        echo "Do: "$PROGNAME" -e ... to rotate these logs"
        echo
        ;;
        
    h )	helptext
	graceful_exit 
	;;

    * )	usage
	exit 1

    esac

done

graceful_exit

##########################################################################
#   Everything below this is ignored
##########################################################################

