#!/usr/local/bin/perl5
#
# This is used for an environment where you use nntpget.  You can make sure 
# your newsgroup listing is synced with a remote site.
#
# Matt Midboe matt@garply.com

use News::NNTPClient;

$active_file="/usr/local/news/active";
$pattern="(^alt|^comp|^humanities|^soc|^rec|^news|^talk|^misc|^clari|^gnu|^k12|^sci)";
$ctlinnd="/usr/local/news/bin/ctlinnd";

sub usage {
  print <<END_OF_HELP;
sync [news server]

sync is used to keep two active files in sync. You can set the NNTPSERVER
environment variable to go to different news servers.

END_OF_HELP
  exit(1);
}

# Setup some stuff 
if ($ARGV[0]) { $server=$ARGV[0]; }
  elsif ($ENV{"NNTPSERVER"}) { $server=$ENV{"NNTPSERVER"}; }
  else { &usage; }

# Open our connection to the news server
$c = new News::NNTPClient("$server");
if (!$c->ok) { exit(1); }

# Get the active list from the remote news server
@active = $c->list;

# Go through active list and build associative array for remote groups
foreach (@active) {
  chop;
  ($name,$hi,$lo,$rest)=split(/ /,$_,4); $rem_groups{$name}=$rest;
}

# Grab a local copy of the active file
open(F, "<$active_file");
while(<F>) { 
  chop;
  ($name,$hi,$lo,$rest)=split(/ /,$_,4); $local_groups{$name}=$rest; 
}
close(F);

# Create any newsgroups that we are missing on the local side
foreach $remote_group (keys %rem_groups) {
  if ($remote_group=~/$pattern/) { 
    if (!defined($local_groups{$remote_group})) { 
      print "$ctlinnd newgroup $remote_group $rem_groups{$remote_group}\n";
    }
  }
}

# Remove any newsgroups that the remote side has deleted
foreach $local_group (keys %local_groups) {
  if ($local_group=~/$pattern/) {
    if (!defined($rem_groups{$local_group})) {
      print "$ctlinnd rmgroup $local_group\n";
    }
  }
}

# Change any group restrictions that need to be changed
foreach $remote_group (keys %rem_groups) {
  if ($remote_group=~/$pattern/) {
    if (($local_groups{$remote_group}) && ($local_groups{$remote_group} ne $rem_groups{$remote_group})) {
      print "$ctlinnd changegroup $remote_group $rem_groups{$remote_group}\n";
    }
  }
}
