#!/usr/net/bin/perl
# Srch.cgi version 0.1
# This is a CGI script which receives a query and pathinfo specifying
# a file consisting of lines of the form Title<tab>URL. It prints a
# response file to stdout replacing the token $QUERY with the query passed
# to it an the line containing $MATCHES with an unorderd list of URLs
# for matching documents.  If the query is empty it prints a coversheet.
# If the list file contains entries of the form Title<tab>URL<tab>filepath,
# then the file referenced by filepath is grepped for the query string instead
# of seeking a match in the title field.

# This program has been placed in the public domain by its author
# John Franks


$pathinfo = $ENV{PATH_INFO};  # Get the argument from the URL
$listfile = $ENV{PATH_TRANSLATED};  # Get the argument from the URL
$coverfile = $listfile.".cover";
$responsefile = $listfile.".response";
$query = $ENV{QUERY_STRING};
$query =~ s/%([\da-f]{1,2})/pack(C,hex($1))/eig;

if ( $query eq "") {
	open (COVER, $coverfile) 
		|| &punt( "Couldn't open cover file $coverfile.\n");
	print "Content-type: text/html\n\n";
	print "Got here\n";
	while ( $line = <COVER> ) {
		print $line;
	}
	exit( 0);
}

open (LISTFILE, $listfile) || &punt( "Couldn't open list file: $listfile.\n");
open (RESPONSE, $responsefile) || &punt( "Couldn't open response file.\n");

print "Content-type: text/html\n\n";

while ( $line = <RESPONSE> ) {
	$line =~ s/\$QUERY/$query/;
	if ( $line =~ /^\$MATCHES/) {
		&matches;
	}
	else {
		print $line;
	}
}

sub matches 
{
	local( $foundmatch);
	$foundmatch = 0;
	LINE:
	while ( $listline = <LISTFILE> ) {
		chop $listline;
		$listline =~ s/\s*#.*$//;
		next LINE if ( $listline eq "");

		( $title, $url, $filepath ) = split( /\t/, $listline, 3);
		if ( $filepath ) {
			open( GREPFILE, $filepath)
				|| &punt( "Couldn't open file to grep.\n");
			while ( <GREPFILE> ) {
				if ($_ =~ /$query/i) {
					if ( !$foundmatch) {
						print "<UL>\n";
						$foundmatch = 1;
					}
					printf( "<LI><A HREF=\"%s\"> %s</A>\n",
						$url, $title);
					next LINE;
				}
			}
		}
		else {
			if ( $title =~ /$query/i) {
				if ( !$foundmatch) {
					print "<UL>\n";
					$foundmatch = 1;
				}
				printf( "<LI><A HREF=\"%s\"> %s</A>\n",
					$url, $title);
			}
		}
	}
	if ( $foundmatch) {
		print "</UL>\n<P>\n";
	} else {
		print "<B>Sorry no matches were found.</B> <P>\n";
	}
}

sub punt
{
	print "Content-type: text/html\n\n";
	printf( "<HEAD><TITLE>500 %s</TITLE></HEAD>\n", @_);
	printf( "<BODY><H2>Error code 500</H2>\n%s\n</BODY>\n", @_);
	exit( 1);
}
