#! /bin/sh
:
#ident	"@(#)smail/util:RELEASE-3_2_0_115:logsumm.sh,v 1.3 2003/06/17 19:19:30 woods Exp"
#
# 	logsumm - daily logfile summary for Smail
#
# Attempts to summarize log files generated when SMAIL_LOG_STYLE=2

# common location
PATH="/usr/lib/smail:/usr/sbin:/bin:/usr/bin"; export PATH

: ${SMAIL_PROGRAM:="/usr/sbin/smail"}
: ${UTIL_BIN_DIR:="/usr/lib/smail"}
: ${DOT_Z:=".gz"}
: ${ZCAT:="gunzip -c"}
: ${TMPDIR:="/var/mail/tmp"}

argv0=`basename $0`

GETOPT=${UTIL_BIN_DIR}/getopt
LOGSUMM_AWK=${UTIL_BIN_DIR}/logsumm.awk

USAGE="Usage: $argv0 [-v] [-E] [-L logsumm.awk] [-t tmpdir] [logfile ...]"

# gawk-3.1.1 is twice as slow as mawk-1.3.3
# The One True AWK (20001115) is in the middle
#
# WARNING:  Old AWK and old NAWK are not compatible with the
# command-line syntax used to invoke awk by this script (-v).
# (newer NAWKs, e.g. on SunOS-5.6 and newer, as well as of course
# those adapted to be XPG-4 compatible, work just fine though)
#
AWK=${AWK:-awk}

SMAIL_LIB_DIR=`${SMAIL_PROGRAM} -bP smail_lib_dir`
LOGFILE=`${SMAIL_PROGRAM} -bP logfile`
# Old fashioned smaillog form
OLD_LOGFILE=`echo ${LOGFILE} | sed -e 's,^\(.*\)/\([^/][^/]*\)$,\1/OLD/\2,'`

# By default we look at "yesterday's" logfile (assuming it's only
# rolled just prior to the time this script is run).
#
if [ -f ${LOGFILE}.0 ]; then
	STATS_LOGS=${LOGFILE}.0
elif [ -f ${LOGFILE}.0${DOT_Z} ]; then
	STATS_LOGS=${LOGFILE}.0${DOT_Z}
elif [ -f ${OLD_LOGFILE}.0 ]; then
	STATS_LOGS=${OLD_LOGFILE}.0
elif [ -f ${OLD_LOGFILE}.0${DOT_Z} ]; then
	STATS_LOGS=${OLD_LOGFILE}.0${DOT_Z}
fi

errors=0			# initialises an awk variable
verbose=0			# initialises an awk variable

OPTIONS="EL:t:v"
set -- `${GETOPT} -n $argv0 -q ${OPTIONS} ${1+"$@"}`
if [ "$?" -ne 0 ]; then
	echo ${USAGE} 1>&2
	exit 2
fi
for i in ${1+"$@"} ; do
	case "$i" in
	-E)
		errors=1
		shift
		;;
	-L)
		LOGSUMM_AWK=$2
		shift 2
		;;
	-t)
		TMPDIR=$2
		shift 2
		;;
	-v)
		verbose=1
		shift
		;;
	--)
		shift
		break
		;;
	-?)
		echo ${USAGE} 1>&2
		exit 2
		;;
	esac
done

if [ $# -ne 0 ] ; then
	STATS_LOGS=${1+"$@"}
fi

if [ ! -d ${TMPDIR} ] ; then
	if mkdir ${TMPDIR} ; then
		chmod 700 ${TMPDIR}
	else
		echo "$argv0: ${TMPDIR} may exist as a file!" 1>&2
		exit 1
	fi
fi

# Try to process the logs in cronological order...
#
STATS_LOGS=`ls -1rt ${STATS_LOGS}`

for LOGFILE in ${STATS_LOGS} ; do
	case ${LOGFILE} in
	*${DOT_Z})
		CAT_STATS_LOG="${ZCAT}"
		;;
	*)
		CAT_STATS_LOG="cat"
		;;
	esac
	${CAT_STATS_LOG} ${LOGFILE}
done | ${AWK} -v VERBOSE=${verbose} -v ERRORS=${errors} -v TMPDIR=${TMPDIR} -f ${LOGSUMM_AWK}

exit 0
