#!/bin/sh
ARCHIVEFILES="all.log"
LOGDIR="/srv/log"
DATE=`date +%Y-%m-%d`
YEAR=`date +%Y`
ARCHIVEDIR="/srv/log/archive/"  #archivedlogs will be in this 
                                #directory + $YEAR 
umask 027

myerror(){
    echo "Error: $*" 1>&2
    exit 1
}

archive_log(){
    FILE="${1}"
    DEST="${2}"

    if [ -f "${DEST}" -o -f "${DEST}.gz" ]; then
        echo "Skipping ${FILE}: Archive already exists" 1>&2
    else
        echo "Archiving file ${FILE} to ${DEST}"
        mv "${FILE}" "${DEST}"
        touch ${FILE}
        LOGS="${LOGS} ${DEST}"
    fi
}

restart_syslog(){
    for i in syslog.pid rsyslogd.pid syslogd.pid ; do
	if [ -f "/var/run/$i" ]; then
	    PIDFILE="/var/run/$i"
	    break
	fi
    done
    if [ "blah${PIDFILE}" = "blah" ]; then
	myerror "Cannot find syslog pid file" 1>&2
    fi
    kill -HUP `cat ${PIDFILE}`
}
archive(){
    [ -d ${LOGDIR} ] || myerror "No such direcroty: ${LOGDIR}"
    [ -d "${ARCHIVEDIR}" ] || myerror "No such archive directory: ${ARCHIVEDIR}"
    [ -d "${ARCHIVEDIR}/${YEAR}" ] || mkdir ${ARCHIVEDIR}/${YEAR}
    ARCHIVEDIR="${ARCHIVEDIR}/${YEAR}"
    
    for logfile in ${ARCHIVEFILES} ; do
        [ -f "${LOGDIR}/${logfile}" ] || myerror "File not found: ${logfile}"
        archive_log "${LOGDIR}/${logfile}" "${ARCHIVEDIR}/${logfile}.${DATE}"
    done
    restart_syslog
    for zipfile in ${ARCHIVEFILES} ; do
        gzip -f "${ARCHIVEDIR}/${zipfile}.${DATE}" || myerror "Error while gzipping ${ARCHIVEDIR}/${zipfile}"
    done
}

case "x$1" in 
    "x-v"|"x--verbose")
    archive 
    ;;
    *) 
    archive >> /dev/null
    ;;
esac
