#!/usr/local/bin/perl

#----------------------------------------------------------------------
# variables you should change, note that archie server is set dynamically below:

$archie_server = "archie.sura.net";
$archie_prog   = "/usr/local/bin/archie";
$ftp_gateway   = "joeboy.micro.umn.edu";
$ftp_port      = 70;

@sound_types   = (".snd$",  ".au$");
@image_types   = (".gif$", ".tiff$", ".pcx$", ".jpg$");
@binary_types  = (".exe$", ".tar.Z$", ".zip$", ".zoo$", ".arj$", ".arc$",
		  ".lzh$", ".hyp", ".pak$", ".exe$", ".com$");
@hqx_types     = (".hqx$");



#----------------------------------------------------------------------

# gateway from gopher to archie
# this is the "brute force" kind of approach; a tidier solution
# would speak the prospero protocols directly.

$archie = "archie.sura.net";
$type = "exact";


sub archie_main {
    
    local($_) = @_;
    
    if (/^$/) {
	&Greply("7Exact search of archive sites on the internet\t$Ggw exact\t$Ghost\t$Gport");
	&Greply("7Substring search of archive sites on the internet\t$Ggw substr\t$Ghost\t$Gport");
	&Greply(".");
	exit;
    }
    
    ($type, $query, $gplus) = split('\t');

    $query =~ s/([^A-Za-z0-9])/\\$1/g;

    @DaytoMon  = ("", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
    
    
    if ($gplus eq '!') {
	print ".\r\n";
	exit;
    }
    
    if ($type eq "exact") {
	$arg = " -e ";
    } else {
	$arg = " -s ";
    }

    exit if (length($query) <1);

    &Greply("0Starting Archie Search, patience.....\t\tbogusip.micro.umn.edu\t70");

    #
    # This code does load balancing, it's worth it, beleive me..
    #
    @archies = ("archie.unl.edu", "archie.sura.net", "archie.ans.net", "archie.rutgers.edu");
    $archiemap{"unl"} = "archie.unl.edu";
    $archiemap{"sura"} = "archie.sura.net";
    $archiemap{"ans"} = "archie.ans.net";
    $archiemap{"rutge"} = "archie.rutgers.edu";

    open(moo, "/usr/ucb/rup @archies|");
    $load = 10000.0;
    $litehost = "sura";
    while (<moo>) {
        m/^archie\.([^\. ]*)[\. ^u].*load average: ([0-9\.^ ]*)/;
        if ($2 < $load) {
                $load = $2;
                $litehost = $1;
        }
    }

    close(moo);
    $archie_server =  $archiemap{$litehost} ;

    &Greply("OSearching Archie server at $archie_server\t\tbogusip.micro.umn.edu\t70");
    
    $archcmd = "$archie_prog -l -t $arg -h $archie_server $query";
    @result = `$archcmd`;
    foreach (@result) {
	($time, $size, $host, $file) = split;
	$type = 0;  # assume text.
	$type = "1" if ($file =~ m./$.) ;
        foreach $i (@binary_types) {
		$type = "9" if ($file =~ /$i/i);
	}
        foreach $i (@image_types) {
		$type = "I" if ($file =~ /$i/i);
	}
        foreach $i (@sound_types) {
		$type = "s" if ($file =~ /$i/i);
	}
        foreach $i (@hqx_types) {
		$type = "4" if ($file =~ /$i/i);
	}
	
	&Greply("$type$host:$file\tftp:$host@$file\t$ftp_gateway\t$ftp_port");
    }
    
    print ".\r\n";
    exit;
    
}

1; # for reqiure
