#!/bin/bash
#
#####
#####  Written by Paul A. Luzzi - on 09-13-2000
#####
#####  Purpose is to archive the mail for some of the users to a logs area.
#####    The intent of this was for the root user, but it could be used for
#####    any user or list of users.
#####

#####
#####  Setup env variables to make portable.
#####    Get the date, set the logs directory, etc.
#####
CURR_DATE=` date '+%m%d%Y' `
MAIL_DIR=/var/spool/mail
MAIL_ARCH_BASE_DIR=/var/log/`uname -n`
MAIL_ARCH_DIR=${MAIL_ARCH_BASE_DIR}/mail_archives
PATH=$PATH:/usr/sbin:/usr/local/sbin:/usr/local/bin:/bin:/usr/bin

#####
#####  Unset some Linux aliases
#####
unalias rm
unalias cp
unalias mv

#####
#####  Create/Get list of users to archive ....
#####
MAIL_USER_LIST="root uucp sys adm lp"

#####
#####  Check that the directory already exists or not ....
#####
if [ ! -d "$MAIL_ARCH_DIR" ]
  then
    if [ ! -d "$MAIL_ARCH_BASE_DIR" ]
      then
        echo "$MAIL_ARCH_BASE_DIR does not exist - creating and changing perms .... \c"
        mkdir "$MAIL_ARCH_BASE_DIR"
        chmod 664 "$MAIL_ARCH_BASE_DIR"
        echo "Done."
      fi
    echo "$MAIL_ARCH_DIR does not exist - create/change perms .... \c"
    mkdir "$MAIL_ARCH_DIR"
    chmod 664 "$MAIL_ARCH_DIR"
    echo "Done."
  fi

#####
#####  Go to the logs directory, and clear any files in the way.
#####
echo "Switching to ${MAIL_DIR} directory .... \c"
cd ${MAIL_DIR}
echo "Done."

#####
#####  Loop thru the users in the list for this ....
#####
for MAIL_USER in ${MAIL_USER_LIST}
  do
    if [ -s "${MAIL_DIR}/${MAIL_USER}" ]
      then
        #####
        #####  Begin by moving existing mail file to archives area
        #####
        echo "\nMoving ${MAIL_DIR}/${MAIL_USER} to ${MAIL_ARCH_DIR}/${MAIL_USER} .... \c"
        cp ${MAIL_DIR}/${MAIL_USER} ${MAIL_ARCH_DIR}/${MAIL_USER}.${CURR_DATE}
        echo "Done."

        #####
        #####  now clear out the original mail 
        #####
        echo "Clearing out ${MAIL_DIR}/${MAIL_USER} .... \c"
        cp /dev/null ${MAIL_DIR}/${MAIL_USER}
        echo "Done."

        #####
        #####  now gzip it down to a reasonable size
        #####
        echo "Gzipping ${MAIL_ARCH_DIR}/${MAIL_USER}.${CURR_DATE} .... \c"
        gzip -9 ${MAIL_ARCH_DIR}/${MAIL_USER}.${CURR_DATE}
        echo "Done."

      fi
  done

#####
#####  End of arch_mail.sh
#####
