#!/usr/bin/perl

use strict;
use Fcntl qw(O_WRONLY O_CREAT O_EXCL O_TRUNC);
use Net::NNTP;

my @merge;
my %last;
my $debug = 0;
my $send = 0;
my $fail = 0;
my $dups = 0;

chdir "/opt/inn/local/get" || die "unable to chdir\n";

die "Already running\n"
	if -f "uu.last.new";

# Now get the groups we want to process
while (<STDIN>) {
	chomp;
	push @merge, $_;
}

# now we have the groups in place, open a connection to the local
# and remote news-servers
my $nntp = Net::NNTP->new("localhost");
defined($nntp) || die "Unable to connect to local newshost\n";
my $master = Net::NNTP->new("localhost", ( Port => 120, Reader => 0, Debug => $debug ));
defined($master) || die "Unable to connect to remote newshost\n";

open(LAST, "uu.last");
while (<LAST>) {
	chomp;
	my ($group,$last) = split(/:/);
	$last{$group} = $last;
}
close(LAST);

open(OUT,">uu.last.new") || die "Unable to create 'uu.last.new'\n";
foreach my $group (@merge) {
	my ($gcnt,$gfirst,$glast) = $nntp->group($group);
	print OUT "$group:$glast\n";

	if (defined $last{$group}) {
		my $first = $last{$group}+1;
		next if $first > $glast;

		print "$group $first to $glast\n";
		my $hdrs = $nntp->xhdr("Message-ID", $first);
		foreach my $key (sort keys %{$hdrs}) {
			my $mid = ${$hdrs}{$key};
			if ($master->ihave( $mid )) {
				print "transfer: $key\n";

				my $art = $nntp->article($key);
				# we NEED an article, so make it empty
				if (!defined($art)) {
					print "transfer: read failed:",$nntp->message(),"\n";
					$art = \[""];
				}

				$master->debug(0);
				$master->datasend($art);
				$master->debug($debug);
				if ($master->dataend) {
					$send++;
				} else {
					$fail++;
				}
			}
			else { $dups++; }
		}
	}
}
close(OUT);
rename "uu.last", "uu.last.bak";
rename "uu.last.new", "uu.last";

printf "%d articles: %d transfered, %d failed and %d dups\n",
	$send+$fail+$dups,$send,$fail,$dups;
