#!/afs/athena/contrib/perl5/p -w

use FileHandle;
use Net::FTP;
use strict;

use vars qw( $CTAN %ftp );
$CTAN = 'ftp.duke.edu:/tex-archive/';	# should end with a '/' !

sub user {
  $ENV{'USER'} || $ENV{'LOGNAME'} || getpwuid($<);
}

sub grab {
  my ($host, $path) = split(/:/, shift, 2);
  $host = lc($host);

  ($host && $path) || return undef;

  if (! $ftp{$host}) {
    print "OPENING HOST: $host\n";

    $ftp{$host} = new Net::FTP $host, @_;
    $ftp{$host} || return undef;

    $ftp{$host}->login('anonymous', '-' . user . '@mit.edu')
      || ($ftp{$host}->quit, return undef);

    $ftp{$host}->binary;
  }

  print "GETTING: $host:$path\n";
  $ftp{$host}->get($path)
    || (print "trying again...\n" && 0)
      || $ftp{$host}->get($path)
	|| die "can't suck over $host:$path";
}

sub wrapup {
  my $host;
  foreach $host (keys %ftp) {
    print "CLOSING HOST: $host\n";
    $ftp{$host}->quit;
    delete $ftp{$host};
  }
}

@ARGV = ('TARFILES')  unless @ARGV;

my $file;

LINE:
while (<>) {
  /^\s*[\#\%\!\$]/ && next LINE;

  ($file) = split(/\s+/);
  ($file eq '') && next  LINE;

  $file =~ s/^CTAN:/$CTAN/;

  grab($file) || die "couldn't grab $file";
} 

wrapup;
