#!/afs/athena/contrib/perl/p

$|=1;
while(<>){
    chop;
    tr/A-Z/a-z/;
    ($name, $port) = split(':', $_);
    @host = split('\.', $name);

    $alpha{$_} = join('.', reverse @host);
#    print("$_ becomes $alpha{$_}\n");
}

@sites = sort bydom keys %alpha;

sub bydom { 
#print("$a ($alpha{$a}) vs. $b ($alpha{$b})\"", $alpha{$a} gt $alpha{$b}, "\"\n"); 
$result = 0 if $alpha{$a} eq $alpha{$b}; 
$result = 1 if $alpha{$a} gt $alpha{$b};
$result = -1 if $alpha{$a} lt $alpha{$b};
$result;
}
print("<ul>\n");
for $s (@sites){
    ($host, $port) = split(/:/, $s);
    (@domparts) = split(/\./, $host);
    $tdom = $domparts[$#domparts];
    $tdom = "num" unless $tdom =~ /[a-zA-Z]/;
    if($tdom ne $ldom){
	$translation = &whois_lookup("$tdom"."-dom");
	print("<h2>$translation</h2>\n");
    }
    if($tdom eq "edu"){
	$tedom = $domparts[$#domparts-1];
	if($tedom ne $ledom){
	    $translation = &whois_lookup("$tedom".".edu");
	    print("<h3>$translation</h3>\n");
	}
    }

    print("<li><a href=\"http://$s/\">$s</a>\n");
    $ldom = $tdom;
    $ledom = $tedom;
}

print("</ul>\n");

sub whois_lookup {
    local($domain) = @_;

    return $Whois{$domain} if $Whois{$domain};
    return "--------------------" if $domain eq "";
    return "Numerical IP address" if $domain eq "num";

    open(WH, "whois -h internic.net \"$domain\"|");
    while(<WH>){
        if(/MILES, JAMES/){
            return "--------------------";
        }
        if(/(.+) \([A-Z\-1-9]+\)/){
            $Whois{$domain} = $1." [$domain]";
            return $1." [$domain]";
        }
        if(/No match for/){
            $Whois{$domain} = "Unknown [$domain]";
            return "Unknown [$domain]";
        }
        if(/system load/){
            return "NIC is overloaded";
        }
    }
    close(WH);
    "Hey, what gives? [$domain]";
}
