#! /usr/bin/perl
#
# J. Uckelman (uckelman@nomic.net)
# 15 January 2001
#

my @query = split /=|&/, $ENV{'QUERY_STRING'};

chdir '..';

my $pattern = '';
my $case = 0;
my @page = ();

while ($tmp = shift @query) {
	if ($tmp eq 'pattern') { $pattern = shift @query; }
	elsif ('on' eq shift @query) {
		if ($tmp eq 'case') { $case = 1; }
		elsif ($tmp eq 'rules') { push @ARGV, <Rules.*>; push @page, "\u$tmp"; }
		elsif ($tmp eq 'events') { push @ARGV, <Event*>; push @page, "\u$tmp"; }
		elsif ($tmp eq 'proposals') { push @ARGV, <Proposals.*>; push @page, "\u$tmp"; }
		elsif ($tmp eq 'motions') { push @ARGV, <Motions.*>; push @page, "\u$tmp"; }
		elsif ($tmp eq 'judgments') { push @ARGV, <Judgments.*>; push @page, "\u$tmp"; }
		elsif ($tmp eq 'roster') { push @ARGV, <Roster.*>; push @page, "\u$tmp"; }
		elsif ($tmp eq 'officer') { push @ARGV, <Officers.*>; push @page, "\u$tmp"; }
		elsif ($tmp eq 'standings') { push @ARGV, <Standings.*>; push @page, "\u$tmp"; }
		elsif ($tmp eq 'lists') { push @ARGV, <lists/*>; push @page, "\u$tmp"; }
		elsif ($tmp eq 'scripts') { push @ARGV, <scripts/*>; push @page, "\u$tmp"; }
	}
}

$pattern =~ s/%(..)/pack("c", hex($1))/ge;
$pattern =~ s/\+/ /g;

print <<END;
Content-Type: text/html\n

<html>
<head>
<title>Search Results</title>
</head>
<body>
<h3>Results for search '$pattern'
END

print ' (case ', $case ? '' : 'in', 'sensitive) in ', (join ', ', @page), ':</h3>'; 

my $line = '';
my @file = ();
my $output = '';

while (<>) {
	$line = $_;
	$line =~ s/<.*?>/ /g;
	if (($line =~ m/$pattern/o and $case) or ($line =~ m/$pattern/io and (! $case))) {
		if ((join ' ', @file) !~ m/$ARGV/) {
			push @file, $ARGV;
			$output .= "<p><a href=\"http://www.nomic.net/~g1/$ARGV\">$ARGV</a><br>";
		}
		if ($case) { $line =~ s/$pattern/<b>$&<\/b>/og; }
		else { $line =~ s/$pattern/<b>$&<\/b>/iog; }
		$output .= "<font size=-1>$line</font><br>";
	}
}

if (! $#ARGV) { print '<p>No pages selected for search.'; }
else { print ($output eq '' ? '<p>No matches' : $output); }

print <<END;
</body>
</html>
END

