#!/bin/sh
#
# cron script to perform monthly login accounting.
#
# Written by Ian A. Murdock <imurdock@gnu.ai.mit.edu>
# Modified by Dirk Eddelbuettel <edd@debian.org>   
# Modified by Tero Tilus <terotil@www.haapavesi.fi>
#   patch adopted by Christian Perrier <bubulle@debian.org> for #187538

LOGROTATE=/etc/cron.daily/logrotate
DAEMON=/usr/sbin/accton
REPORTFILE=/var/log/wtmp.report
ACCT_MONTHLY_CYCLE=0

test -x $DAEMON || exit 0

if [ -f /etc/default/acct ]
then
	. /etc/default/acct
fi

if [ -f $REPORTFILE ]
then
	test $ACCT_MONTHLY_CYCLE -gt 1 && \
	savelog -g adm -m 0640 -u root -c $ACCT_MONTHLY_CYCLE \
		$REPORTFILE > /dev/null
fi

echo "Login accounting for the month ended `date`:" > /var/log/wtmp.report
echo >> /var/log/wtmp.report

# The logrotate script happens to run before this one, effectively 
# swallowing all information out of wtmp before we can use it. 
# Hence, we need to use the previous file. Bad hack.
# Too bad we never heard from the logrotate maintainer about this ...

# edd 18 May 2002  make sure wtmp.1 exists

if [ -f $LOGROTATE ] && [ -x /usr/sbin/logrotate ]
then
	if [ -f /var/log/wtmp.1 ]; then
		WTMP=/var/log/wtmp.1
	elif [ -f /var/log/wtmp.1.gz ]; then
		WTMP_WAS_GZIPPED=1
		WTMP=`tempfile`
		gunzip -c /var/log/wtmp.1.gz > $WTMP
	fi

	ac -f $WTMP -p | sort -nrk 2 >> $REPORTFILE
	echo >> $REPORTFILE
	last -f $WTMP >> $REPORTFILE

	if [ -n "$WTMP_WAS_GZIPPED" ]
	then
		# remove temporary file
		rm -f $WTMP
	fi
else
	ac -p | sort -nrk 2 >> $REPORTFILE
	echo >> $REPORTFILE
	last >> $REPORTFILE
fi

chmod 640 /var/log/wtmp.report
chown root:adm /var/log/wtmp.report
