#!/usr/bin/perl

use CGI qw/:standard/;
use CGI::Carp qw/fatalsToBrowser/;
$query = new CGI;

print header(),
    start_html( -title=>"CMU Computer Club Documentation -- Machines");
    
open(MACHINES, "/afs/club/admin/misc/data");

if (defined $query->param('sort')) {
   if ($query->param('u') eq 'd') {
	$sortdir = -1;
   } else {
	$sortdir = 1;
   }
} else {
   $sortdir = 0;
}

@headings = ( '<a href="index.pl?sort=0">host</a>', '<a href="index.pl?sort=1">IP Address</a>', '<a href="index.pl?sort=2">Contact Person</a>', '<a href="index.pl?sort=3">Net Port</a>', '<a href="index.pl?sort=4">Circuit</a>', 
   '<a href="index.pl?sort=5">Load</a>', '<a href="index.pl?sort=6">Services</a>', "More info" );
$headings[$query->param('sort') + 0] =~ s/">/\&u=d">/ if ($sortdir > 0);
@rows = th[@headings];
@ents = ();

while(<MACHINES>) {

    if(/^\s*$/ || /^\#.*$/) { next; }
    ($host,$addr,$contact,$port,$circuit,$load,$srv) = split(/\t+/);
    $shorthost = (split(/\./, $host))[0];

    if(-r "/afs/club/public/doc/machines/$shorthost.html") {
	$moreinfo = a({href=>"$shorthost.html"},"More Info");
    }
    else {
	$moreinfo = "";
    }
    if (-r "/afs/club/public/doc/machines/$shorthost.gone") {
	foreach $foo ($host,$addr,$contact,$port,$circuit,$load,$srv,$moreinfo) {

		$foo = "<strike>".$foo."</strike>"
		if ($foo ne '');
	}
    }

    push(@ents, [$host,$addr,$contact,$port,
		    $circuit,$load,$srv,$moreinfo]);
}

sub cmpstrike {
    my ($a, $b) = @_;
    my ($aa, $bb) = ($a->[0], $b->[0]);
    if ($aa =~ m/^<strike/) {
    	if ($bb =~ m/^<strike/) {
	    return 0;
	}
    return 1;
    }
    if ($bb =~ m/^<strike/) {
    	return -1;
    }
    return 0;
}


if (defined $query->param("sort")) {
    $sortcol = ($query->param("sort")) + 0;
    @ents = sort { &cmpstrike($a, $b) ||
   	 ($a->[$sortcol] cmp $b->[$sortcol])*$sortdir } @ents;
} else {
    @ents = sort { &cmpstrike($a, $b) } @ents;
}

push(@rows, map { td $_ } @ents);

print table(Tr(\@rows));

print end_html();
