#!/bin/sh
# dohisttrim - trim the history file and rebuild the dbz database

##  =()<. @<_PATH_SHELLVARS>@>()=
. /usr/news/etc/innshellvars

##  =()<. @<_PATH_NEWSLIB>@/dexpire.conf>()=
. /usr/news/etc/dexpire.conf

prog=`basename $0`
errs=/tmp/dohist.$$
log=${MOST_LOGS}/histtrim.log

cd `dirname ${HISTORY}`

# Pause the server
mesg="Rebuilding history file"
ctlinnd -s -t120 pause "$mesg" > $errs 2>&1
tstatus=$?
if [ $tstatus != 0 ]; then
	${MAILCMD} -s "$prog problems (ctlinnd pause)" "$DEXPIREMAIL" < $errs
	rm -f $errs
	exit 1
fi
rm -f $errs

# Make room for the new history file.
rm -f history.o history.n

histtrim -duv -m $HISTTRIM_MINDAYS > $log 2> $errs
tstatus=$?
if [ $tstatus != 0 ]; then
	# Release the server
	ctlinnd -s -t120 go "$mesg" >> $errs 2>&1
	(echo "[histtrim exited with $tstatus]" ; cat $errs) |
	    ${MAILCMD} -s "$prog problems (histtrim)" "$DEXPIREMAIL"
	rm -f $errs
	exit 1
fi

if [ -s $errs ]; then
	# Just send mail
	${MAILCMD} -s "$prog problems (histtrim)" "$DEXPIREMAIL" < $errs
fi
rm -f $errs

# Figure out how many entries are in the new history file
num=`awk '$3 == "numread" { print $2 }' $log`
if [ 0$num -le 100 ]; then
	# Didn't get a reasonable value
	t=`wc -l history`
	echo "Bogus new history file size: $num (wc says size is $t)" | \
	    ${MAILCMD} -s "$prog problems (history size)" "$DEXPIREMAIL"
	num=`expr \( 3 \* $t \) / 2`
else
	num=`expr \( 5 \* $num \) / 4`
fi

#
# Avoid an infinite loop in dbztagmask(); limit size to 2^30 / 70 (or 15339168)
#
if [ 0$num -gt 15339168 ]; then
	$num=15339168
fi

makehistory -r -s $num -f history.n > $errs 2>&1

if [ -s $errs ]; then
	${MAILCMD} -s "$prog problems (makehistory)" "$DEXPIREMAIL" < $errs
fi
rm -f $errs

# Rotate old files
mv history history.o
mv history.pag history.o.pag
mv history.dir history.o.dir

# Rotate new files into position
mv history.n history
mv history.n.pag history.pag
mv history.n.dir history.dir

# Remove old dbz files
rm -f history.o.pag history.o.dir

# Reload the history file
ctlinnd -s -t120 reload history "$mesg" > $errs 2>&1
tstatus=$?
if [ $tstatus != 0 ]; then
	${MAILCMD} -s "$prog problems (ctlinnd reload history)" \
	    "$DEXPIREMAIL" < $errs
	rm -f $errs
	exit 1
fi

# Release the server
ctlinnd -s -t120 go "$mesg" > $errs 2>&1
tstatus=$?
if [ $tstatus != 0 ]; then
	${MAILCMD} -s "$prog problems (ctlinnd go)" "$DEXPIREMAIL" < $errs
	rm -f $errs
	exit 1
fi
rm -f $errs

exit 0
