#!/bin/sh
#
# @(#)roller.sh,v 1.3 2005/04/29 13:27:55 kim Exp
#
# Log rolling script.  It treats each argument as a logfile,
# puts the old gzip'ped logs in $logdir/$logname.YYMMDD[.hh:mm:ss].gz,
# creates a new null log, and if a script or program
# named $procdir/proc-$logname exists, it runs
# that script, with the old log (before gzip'ping)
# as the first argument.
# Mark Moraes, D. E. Shaw & Co.
#
# Converted to read a config file of the format
#   logfile pidfile mailto subject
#
# 1996-07-28  Kimmo Suominen
# 1997-01-14  Kimmo Suominen	do not roll empty files (only send HUP)
#
PATH=/usr/pkg/sbin:/usr/pkg/bin:/bin:/usr/bin:/usr/sbin
export PATH

usage="Usage: $0 [-l logdir] [-p procdir]"
basedir=/var/log/OLD
procdir=/usr/pkg/share/roller

while getopts l:p: opt
do
    case "$opt" in
    l)	basedir="$OPTARG";;
    p)	procdir="$OPTARG";;
    *)	echo "$usage" >&2; exit 1;;
    esac
done
shift `expr $OPTIND - 1`
# check we have the right number of args.
case $# in
1)  cfgfile=$1;;
*)  echo "$usage" >&2; exit 1;;
esac

if [ ! -r $cfgfile ]
then
    echo "Cannot read config file $cfgfile" >&2
    exit 2
fi

pid=$$
datedir=`logtime -p | sed -e 's;\(....\)\(..\)\(..\).*;\1/\2/\3;'`
h=`uname -n`
logdir=$basedir/$datedir/$h
mkdir -p $logdir

cat $cfgfile |
while read logfile signame pidfile extras
do
    f=`basename $logfile`
    d=`dirname $logfile`
    case "$d" in '') d=.;; esac
    (
	cd $d &&
	test -s $f &&
	mv $f $f.$pid &&
	touch $f &&
	cpogm $f.$pid $f
    )
    if [ x$pidfile != xnone ]
    then
	read p extras < $pidfile
	if [ 0$p -gt 0 ]
	then
	    if [ x$signame = x- ]
	    then
		signame=HUP
	    fi
	    kill -$signame $p
	fi
    fi
done

# We want to be done with all moving and killing before storing the data,
# so that the daemons have moved to the new files, and a single daemon
# (e.g. syslogd) does not have to be signaled multiple times (only on the
# last file it uses).

t=/tmp/RoLLeR.$pid
cat $cfgfile |
while read logfile signame pidfile mailto subject
do
    f=`basename $logfile`
    if [ -x $procdir/proc-$f -a -r $logfile.$pid ]
    then
	rm -f $t
	$procdir/proc-$f $logfile.$pid > $t 2>&1
	if [ -s $t ]
	then
	    (
		echo "To: $mailto"
		echo "Subject: [$h] $subject"
		echo ""
		cat $t
	    ) | sendmail -t
	fi
	rm -f $t
    fi
done

# We archive the data in the end because some daemons need special signals
# or administrative actions for the logfile to be switched.

cat $cfgfile |
while read logfile extras
do
    if [ -f $logfile.$pid ]
    then
	f=`basename $logfile`
	l=$logdir/$f.gz
	while [ -f $l ]
	do
	    echo $0: $l exists >&2
	    set x `logtime -p`
	    l=$logdir/$f.$3.gz
	    echo $0: trying $l >&2
	done
	gzip --best < $logfile.$pid > $l &&
	cpogm $logfile.$pid $l &&
	rm -f $logfile.$pid
    fi
done
