#!/usr/local/bin/perl5 -s
#
# This file is part of SnarfNews
# Copyright (C) 1991,1992,1993,1994,1995,1996 Alec Muffett
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

require "snarf.pl";

$usage = "gronkmsgids [-debug] hostname[:port] [n]\n";

# hostname[:port] to connect to
$host = shift || die $usage;
$prefetch = shift || 0;

# connect
unless (&OpenNNTP($host))
{
    die "gronkmsgids: cannot open connection to $host\n";
}

# read a line to see if we got a good connection.
if (($_ = &RecvNNTP(0)) !~ /^200/o)
{
    die "gronkmsgids: service unavailable: $_";
}

# in case we run into an INN server
&SendNNTP("MODE reader\n");

if (($_ = &RecvNNTP(0)) !~ /^200/o)
{
    warn "gronkmsgids: server didn't like MODE command: $_";
}

$outstand = 0;

# get list of message-ids
while ($msgid = <STDIN>)
{
    chomp($msgid);

    &SendNNTP("ARTICLE $msgid\n");
    $outstand++;

    if ($prefetch)
    {
	$prefetch--;		# decrement
	next;                   # and start a prefetch
    }

    &SlurpIt;
    $outstand--;
}

while ($outstand > 0)
{
    warn "gronkmsgids: outstanding article $outstand\n" if ($debug);
    &SlurpIt;
    $outstand--;
}

&SendNNTP("QUIT\n");

if (($_ = &RecvNNTP(0)) !~ /^205/o)
{
    warn "gronkmsgids: server didn't like QUIT command: $_";
}

&CloseNNTP;

exit(0);

##################################################################
##################################################################

sub SlurpIt
{
    @article = ();
    $artsize = 0;

    if (($_ = &RecvNNTP(0)) !~ /^220/o)
    {
	warn "gronkmsgids: missing article: $_";
	return;
    }

    while ($_ = &RecvNNTP(3))
    {
	last if ($_ eq ".\n");
	s/^\.\./\./o;
	push(@article, $_);
	$artsize += length($_);
    }

    if ($debug)
    {
	printf(STDERR "- article: %d bytes\n", $artsize);
    }

    print "#! rnews $artsize\n", @article;
}
