#!/bin/sh
# @(#)$Id: trim_wtmp 2.0 2001/12/20 litmaath@fnal.gov $
#
# trim_wtmp - keep wtmp files at reasonable lengths
#
# example crontab entry:
#
# 25 5 * * * /usr/local/adm/trim_wtmp -k 40000
#

PATH=/bin:$PATH
export PATH

usage()
{
    echo "Usage: $0 [-k entries_kept] [-f]" >&2
    exit 1
}

override=false
min_entries=2000
entries=$min_entries
dir=/var/adm

#
# the number of bytes per wtmp/wtmpx record depends on OS and release...
# check /usr/include/utmp*.h
#

case `uname`-`uname -r` in
OSF1-V5*)
    record_wtmp=392
    record_wtmpx=384
    ;;
OSF1-V4*)
    record_wtmp=156
    record_wtmpx=164
    ;;
Linux-*)
    record_wtmp=384
    record_wtmpx=384
    dir=/var/log
    ;;
*)
    #
    # e.g. Solaris, IRIX
    #
    record_wtmp=36
    record_wtmpx=372
esac

while test $# != 0
do
    case $1 in
    -f)
	override=true
	;;
    -k)
	shift
	entries=$1
	;;
    *)
	echo "$0: illegal argument: $1" >&2
	usage
    esac
    test $# != 0 && shift
done

test "x$entries" = x && usage
expr "0$entries" : '.*[^0-9]' > /dev/null && usage

if test $entries -lt $min_entries && test $override = false
then
    echo "$0: number of entries raised from $entries to $min_entries" >&2
    entries=$min_entries
fi

cd $dir
umask 002
tmp=/tmp/tmp_wtmp_`date +%H%M%S`_$$
mkdir $tmp

for i in wtmp wtmpx
do
    test -f $i || continue

    eval record=\$record_$i
    size=`expr $entries '*' $record`

    set x `wc -c < $i`
    shift

    test "0$1" -gt $size || continue

    #
    # portable way to copy mode and ownership...
    #

    tar cf - $i | (cd $tmp && tar xfBp -)

    skip=`expr '(' "$1" - $size ')' / $record`

    dd ibs=$record skip=$skip if=$i of=$tmp/$i 2>&1 |
	egrep -v '^[0-9]+\+[01] records (in|out)$' || mv $tmp/$i .
done

rmdir $tmp