#!/bin/sh
# @(#) $Header: dohisttrim.cnews,v 1.6 96/05/22 21:39:27 leres Exp $ (LBL)
# dohisttrim - trim the history file and rebuild the dbz database
# (C News version)

# =()<. ${NEWSCONFIG-@<NEWSCONFIG>@}>()=
. ${NEWSCONFIG-/usr/new/lib/news/bin/config}

# Needed by new spacefor
export NEWSCTL NEWSARTS

PATH=$NEWSCTL/bin:$NEWSBIN/expire:$NEWSBIN:$NEWSPATH ; export PATH
umask $NEWSUMASK
prog=`basename $0`

cd $NEWSCTL

lock="$NEWSCTL/LOCK"
ltemp="$NEWSCTL/L.$$"
echo $$ >$ltemp
trap "rm -f $ltemp ; exit 0" 0 1 2 15
until newslock $ltemp $lock; do sleep 1; done
trap "rm -f $ltemp $lock ; exit 0" 0 1 2 15

size="`sizeof history history.pag history.dir`"
if test " `spacefor $size control`" -le 0; then
	cat <<EOF | /bin/mail "$NEWSMASTER"
Subject: $prog problems

SEVERE SPACE SHORTAGE in $NEWSCTL! ($size bytes needed)
Unable to rebuild history files due to insufficient space for
temporaries. Since dexpire doesn't free space in this partition,
human action is urgently needed.
EOF
	exit 1
fi

errs="dohist.$$"
histtrim -duv -m 20 > histtrim.log 2> $errs

# XXX check exit status too?
if test -s $errs
then
	rm -f $ltemp $lock
	(echo "Subject: $prog problems"
	echo ""
	cat $errs ) | /bin/mail "$NEWSMASTER"
	rm -f $errs
	exit 1
fi
rm -f $errs

mkdbm history.n 2> $errs
if test -s $errs
then
	rm -f $ltemp $lock
	(echo "Subject: $prog problems (mkdbm)"
	echo ""
	cat $errs ) | /bin/mail "$NEWSMASTER"
	rm -f $errs
	exit 1
fi
rm -f $errs

# Rotate old files
rm -f history.o
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

# Unlock news system
rm -f $ltemp $lock

exit 0
