#! /bin/sh
# Prepare some batches of size $1 in files named togo.[0-9] .  We prepare a
# total of 7 to stay within awk's limits on file descriptors (we need a
# couple of other descriptors).  Source is file togo.next if it exists, or
# togo if not.  If there is no togo.next and there is more in togo than will
# fit in the numbered batches, put the next few lots in togo.next.  This
# avoids the need to paw through the whole togo file every time when a large
# backlog has built up.
#
# Buglet:  does not count the "#! rnews nnnnn" headers in sizes.
#
# If the togo file does not contain file sizes, we make an arbitrary guess
# at an average size.

case $#
in
	0)
	echo 'Usage: batchsplit size' >&2
	exit 2
	;;
esac

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

PATH=$NEWSCTL/bin:$NEWSBIN/batch:$NEWSBIN:$NEWSPATH ; export PATH
umask $NEWSUMASK

# Locking.
lock="$NEWSCTL/LOCK"
ltemp="$NEWSCTL/L.$$"
echo $$ >$ltemp
trap "rm -f $ltemp ; exit 0" 0 1 2 15
while true
do
	if newslock $ltemp $lock
	then
		trap "rm -f $ltemp $lock ; exit 0" 0 1 2 15
		break
	fi
	sleep 30
done

rm -f togo.overflow togo.count
if test -s togo.next
then
	input=togo.next
else
	input=togo
fi

awk 'BEGIN { total = 0 ; ninbatch = 0 ; bno = 1 ; limit = '$1'
		batch = "togo." bno ; nbatches = 7 }
	{
		if (NF == 1)
			size = 3000	# Arbitrary guess.
		else
			size = $2
		if (total + size > limit && ninbatch > 0) {
			# Go to next batch.
			bno++
			if (bno <= nbatches) {
				batch = "togo." bno
				ninbatch = 0
			} else if (bno == nbatches+1 && FILENAME == "togo") {
				batch = "togo.next"
				limit = 4 * nbatches * limit
			} else {
				print NR - 1 >"togo.count"
				exit
			}
			total = 0
		}
		ninbatch++
		total += size
		print >batch
	}' $input

if test -s togo.count
then
	sed "1,`cat togo.count`d" $input >togo.overflow
	rm togo.count
fi

if test -r togo.overflow
then
	mv togo.overflow $input
else
	>$input
fi
