#! /usr/bin/perl -w
use diagnostics;
use strict;

use Net::NNTP;

my $nntp;

sub usage ()
{
    print STDERR <<"EOF";
Usage: $0 hostname newsgroup-name archive-directory
EOF
    exit 1;
}

sub bail ($)
{
    my $msg = shift;
    $nntp->quit;
    print STDERR "$msg\n";
    exit 1;
}

my $host = shift or usage;
my $group = shift or usage;
my $archive = shift or usage;
-d $archive or usage;

opendir ARCHIVE, $archive or die "can't opendir $archive: $!";
my @list = grep m/^\d+$/, readdir ARCHIVE;
closedir ARCHIVE;

@list = sort { $a <=> $b } @list;
my $start = scalar @list ? $list[$#list] + 1 : 0;

$nntp = Net::NNTP->new($host);
# Bah, password in clear, oh well, it's only passworded to keep the
# howling masses out anyway ...
#$nntp->authinfo('afe', 'MyTest');

my ($narticles, $first, $last, $name) = $nntp->group($group);
(defined $first and defined $last) or bail "Couldn't set group to $group";

exit if $last <= $start;
$start = $first if $first > $start;

for my $index ($start..$last)
{
    my $article = $nntp->article($index);
    if (defined $article)
    {
    	open ARTICLE, ">$archive/$index"
	    or die "can't open $archive/$index for writing: $!";
    	print ARTICLE join '', @$article;
	close ARTICLE;
    }
    #print STDERR "$group $index\n";
}

$nntp->quit;

