#!perl
# search.pl

print "Content-type: text/html\n\n";
print "<html>\n<head>\n<title>Search Results</title>\n</head>\n";
print "<body>\n";
print '
<table border="0" cellpadding="0" cellspacing="0" width="100%">
  <tr>
    <td valign="middle" width="100%" bgcolor="#000080"><font size="+1" face="Verdana,Arial"
    color="#FFFFFF">Search Results</font></td>
  </tr>
</table>
';

$baseurl = "";
$basedir = $ENV{'DOCUMENT_ROOT'};
$basedir =~ s/\/htdocs$//;
$basedir =~ s/\/apache$//;
$basedir .= "/perl";

parse_form();
get_files();
search();
return_html();
exit;




sub parse_form {
   # Get the input
   read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
   # Split the name-value pairs
   @pairs = split(/&/, $buffer);
   foreach $pair (@pairs) {
      ($name, $value) = split(/=/, $pair);
      $value =~ tr/+/ /;
      $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
      $FORM{$name} = $value;
   }
}



sub get_files {
    chdir($basedir);
    @files = scan_dir("html");
    #print "<pre>file=\n", join("\n", @files), "\n";
    foreach $file (@files) {
        if (-T $file) {
            push(@FILES,$file);
        }
    }
}


sub scan_dir {
    my($startingdir) = @_;
    my(@dirs, @files);
    my $f;

    @dirs = $startingdir;
    my $dir;

    while (@dirs) {
        $dir = shift(@dirs);
        opendir(DIR, $dir) || next;
        while (defined($f = readdir(DIR))) {
        	if (-d "$dir/$f" && $f ne "." && $f ne "..") {	    # directory
	            push(@dirs, "$dir/$f");
    	    } elsif (-f "$dir/$f") {
                push(@files, "$dir/$f");
            }
        }
        closedir(DIR);
    } # while
    return sort @files;
}



sub search {
   @terms = split(/\s+/, $FORM{'terms'});
   foreach $FILE (@FILES) {
      open(FILE,"$FILE");
      @LINES = <FILE>;
      close(FILE);
      $string = join(' ',@LINES);
      $string =~ s/\n//g;
      foreach $term (@terms) {
         if ($string =~ /$term/i) {

            if ($string =~ /<title>(.*)<\/title>/i) {
                $title = $1;
            }
            else {
                $title = $FILE;
            }
            $include{$FILE} = $title;

            last;
         }
      }
   }
}
      



sub return_html {

    foreach $key (keys %include) {
        print "<li><a href=\"$baseurl/$key\">$include{$key}</a>\n";
    }
   print "</body>\n</html>\n";
}

