#!/usr/bin/perl

require "find.pl";

if ($ENV{'REQUEST_METHOD'} eq "POST") {
    read(STDIN, $request, $ENV{'CONTENT_LENGTH'});
    }
elsif ($ENV{'REQUEST_METHOD'} eq "GET" ) {
    $request = $ENV{'QUERY_STRING'};
    }

@rqpairs = &url_decode(split(/[&=]/, $request));
@rqsave = splice( @rqpairs, 0, 5 );
$rqpairs = join( " ", @rqpairs );
$rqpairs =~ s/ bookname /,/g;
@rqpairs = split( " ", $rqpairs );
%rqpairs = ( @rqsave, @rqpairs );
@keys = keys %rqpairs;

$input = $rqpairs{"terms"};
(@keywords) = split(' ',$input);

$booknames = $rqpairs{"bookname"};
if( index($booknames,"ALL") >= 0 ){ $booknames="all" };

$case = $rqpairs{"case"};

$caseDesc = ($case ? "case-insensitive" : "case-sensitive");

print "Content-type: text/html\n\n";
print <<"EOF";
<html>
<head>
<title>Text Search Results</title>
</head>
<body bgcolor=#FFFFFF text=#000000>
<center>
<h1>Alias|Wavefront 9.0 Documentation Search Results</h1>
</center>

EOF

for $bookname ( split(/\,/ , $booknames )) {

print <<"EOF";
Your $caseDesc search for <b>$input</b> in <b>$bookname</b>
resulted in the following:<br><br>

<blockquote>
EOF

	if ( $bookname ne "all" )
	{
		&find("./$bookname/");
	}
	else
	{
		&find("./");
	}
	print "</blockquote></body></html>";
}

exit;

# this routine is run by find on each file found.
sub wanted {                                               
	next if -d FILE;
	next unless /\.html/;
	next if /searchbooks.html/;
	next if /Contents.html/;
	next if /Index.html/;

	$filename = $_;

	open(FILE, "$filename") || do {
		print "Error: can't read \"$filename\"<br>\n";
		return;
	};

	$regexp = "(" . join("|", @keywords) . ")";

	for ($i=0; $i < @keywords; $i++) {
		$found[i] = 0;
	}
	$num_found = 0;
	
#	@foo = grep(!/^#/, @bar);
#	@dots = grep { /^\./ && -f "$some_dir/$_" } readdir(DIR);

	if($case eq "i") {
		@found = grep(/$regexp/i, <FILE>);
	} else {
		@found = grep(/$regexp/, <FILE>);
	}

	if(@found) {
		# $name is supplied by the find() routine and has the form
		# $dir/$filename for the file currently being processed
		$header_printed = 0;
		foreach (@found) {
			s!<[^>]+>!!g;
			s!($regexp)!<b><font color=red>$1</font></b>!ig;
			# The found text may have been in the tag
			if ($1) {
				if (!$header_printed) {
					print "<a href=$name>$filename</a>\n";
					print "<ul>\n";
					$header_printed = 1;
				}
				print "<li>";
				print;
				print "<p>\n\n";
			}
		}
		if ($header_printed) {
			print "</ul>\n";
		}
	}
}


sub url_decode {

#   Decode a URL encoded string or array of strings 
#       + -> space
#       %xx -> character xx

    foreach (@_) {
		tr/+/ /;
		s/%(..)/pack("c",hex($1))/ge;
		}
    @_;
}

