#! /bin/sh
# Process spooled news.

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

PATH=$NEWSCTL/bin:$NEWSBIN/input:$NEWSBIN/relay:$NEWSBIN:$NEWSPATH
export PATH

umask $NEWSUMASK

here="$NEWSARTS/in.coming"
cd $here

# First, is it worth trying at all?
if test -r stop
then
	exit 0
fi

# Lock against others running.
lock="$NEWSCTL/LOCKinput"
ltemp="$NEWSCTL/L.$$"
echo $$ >$ltemp
trap "rm -f $ltemp ; exit 0" 0 1 2 15
if newslock $ltemp $lock
then
	trap "rm -f $ltemp $lock ; exit 0" 0 1 2 15
else
	exit 0
fi

# Get rid of any old temporaries.
rm -f nruntmp.*
for f in `ls | egrep '^nspool'`
do
	find $f -mtime +1 -exec rm -f '{}' ';'
done

# Sort out where we are.
me="`hostname`"
if test -r $NEWSCTL/server
then
	server=`cat $NEWSCTL/server`
else
	server="$me"		# no server file --> we're it
fi

# Master loop.
while true
do
	# Find some work.
	them=`ls | egrep '^[0-9]+$' | sort | sed 50q`
	if test "$them" = ""
	then
		break
	fi

	# Do it.
	for f in $them
	do
		# Check for request to stop.
		if test -r stop
		then
			exit 0
		fi

		# Check space.  It is *probably* better to stop processing
		# when things get too full.  (This test is actually a bit
		# inaccurate since the batch may be compressed, but it's
		# good enough to catch major space problems.)
		batchsize=`sizeof $f`
		if test " $batchsize" -eq 0		# empty batch
		then
			rm -f $f
			continue		# ugh
		fi
		if test " `spacefor $batchsize articles`" -le 0
		then
			exit 0
		fi

		# Decompress if necessary.
		text=nruntmp.$$
		if compress -d <$f >$text 2>/dev/null
		then
			rmlist="$f $text"
		elif c7decode <$f 2>/dev/null | compress -d >$text 2>/dev/null
		then
			rmlist="$f $text"
		else
			rm -f $text
			text=$f
			rmlist="$f"
		fi

		# Do it.  -r redirects stdout and stderr into logs.  -n makes
		# history entries for refused articles; this is right for
		# NNTP-feed sites and doesn't hurt uucp-feed sites unless
		# they refuse a good fraction of what they get.

		if test " $server" = " $me"	# if local
		then
			relaynews -r -n <$text
		else
			# N.B.: rsh always returns exit status 0!
			rsh $server "PATH=$PATH relaynews -r -n" <$text
		fi
		st=$?
		if test $st -ne 0
		then
			# trouble
			if test ! -d bad
			then
				mkdir bad
			fi
			bad=bad/$f

			if test -s bad/limit
			then
				limit=`sed 1q bad/limit`
			else
				limit=50
			fi
			nfiles=`ls bad | wc | awk '{print $1}'`
			if test " $nfiles" -lt " $limit"
			then
				mv $f $bad	# Not $text, save the ORIGINAL!
			fi
			echo "$server $consumer \`$bad' failed, status $st" |
							mail "$NEWSMASTER"
		fi

		rm -f $rmlist
	done
done

find bad -mtime +7 -exec rm -f '{}' ';'

exit 0
