#!/afs/athena/contrib/perl5/perl -w
# -*- cperl -*-

use strict;

use vars qw( $ROOT );
$ROOT = ($ENV{'HOME'} || '.') . '/Mail';

@ARGV = ( "$ROOT/.newsrc" ) unless @ARGV;

sub grp2path { my ($arg) = @_; $arg =~ s!\.!/!g; "$ROOT/$arg"; }

while (<>) {
  chomp;
  my ($grp, $delim, $rest) = split /([:!\s])/, $_, 2;
  next if $delim eq '!';  # unsubscribed
  my $path = grp2path $grp;
  warn("No group directory for $grp!\n"), next
    unless -d $path;
  opendir DIR, $path
    or die "opendir($path): $!";

  my ($min,$max);
  while (defined(my $fn = readdir DIR)) {
    next if $fn =~ /\D/;
    ($min = $max = $fn, next) unless defined $min;
    $min = $fn if $min > $fn;
    $max = $fn if $max < $fn;
  }

  if (!defined $min) {
    if ($delim eq ':' or $delim eq '!') {
      # newsrc format
      $max = 0;
      foreach my $curr ($rest =~ /\d+/g) { $max = $curr if $max < $curr; }
      $min = $max + 1;
      warn "group $grp is empty, last seen article was $max\n";
    } else {
      # active format
      ($max, $min) = ($rest =~ /^\s*(\d+)\s+(\d+)/)
	or die "Bad active-format line: '$_'\n";
      warn "group $grp is empty, active bounds are $min-$max\n";
    }
  }

  print "$grp $max $min y\n";

  closedir DIR
    or die "closedir($path): $!";
}
