#!/usr/bin/perl
#Time-stamp: "2005-08-19 01:41:49 ADT" sburke@cpan.org
# desc{  search titles of RFCs  }
#
# Search titles of RFCs.
# E.g.:
#    greprfc coffee
# Returns:
#    2324    Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0)

use strict;
my $db = $0 . '.tsv.gz';

# See http://info.internet.isi.edu/in-notes/rfc/ for all RFC things

unless(-e $db and -M $db < 31) {
  my $local_file = '/tmp/rfc-index.txt';
  eval {
    #ftp://ftp.isi.edu/in-notes/rfc-index.txt
    require Net::FTP;
    my $host = 'ftp.isi.edu';
    my $file = '/in-notes/rfc-index.txt';
    print "Refreshing index from $host$file...\n";
    my $ftp = Net::FTP->new($host);
    die "Can't build connection to $host" unless $ftp;
    
    $ftp->login('anonymous', 'nobody@nowhere.int')
     or die "Can't anon-login to $host";
    $ftp->binary or die "Couldn't set binary mode??";
    $ftp->get($file, $local_file)
     or die "Can't get $file as $local_file";
    $ftp->quit;
    print " Transfer done.\n";
  };
  die "Couldn't refresh index: $@\n" if $@;
  open(IN, "<$local_file") or die "Can't read-open $local_file: $!";
  binmode(IN);
  my $start_seen = 0;
  my $number;
  local $/ = "\cj";
  print " Building index into $db\n";
  while(<IN>) {
    if(m/^0001 /s) {
      seek(IN, -length($_), 1); # back up over this line
      last;
    }
  }
  die "First entry in $local_file never found?\n" if eof(IN);
  $/ = "\cj\cj";
  my @out;
  while(<IN>) {
    if(s/^(\d\d\d\d) //s) {
      $number = 0 + $1;
      $start_seen = 1;
      s/\cj +/ /gs;
      tr/\t\cj/ /d;
      s/\. .+//s;
      unshift @out, "$number\t$_\n";
    } else {
      #print "Skipping <$_>\n";
    }
  }
  close(IN);
  die "Too few RFCs found -- only ", scalar(@out), " but expected at least 2700"
   if @out < 2700;
  open(OUT, "|gzip -f >$db") or die "Can't write-open $db: $!";
  print OUT @out; # starting with the most recent
  close(OUT);
  unlink($local_file);
}
my $pattern;
if(@ARGV and defined $ARGV[0] and length $ARGV[0]) {
  $pattern = $ARGV[0];
  eval { 'foo' =~ m/$pattern/oi };
  die "Error in compiling pattern: $@\n" if $@;
} else {
  die "What pattern?\n";
}

open(IN, "gzip -d < $db|") or die "Can't read-open $db: $!";
while(<IN>) { print $_ if m/$pattern/oi }
close(IN);
exit;

