#!/usr/bin/perl
# Search for words in all OID files, returning a list of them
# as a Web page. Silly!
# Expects to be called as a CGI-BIN script with a ?search argument.
$httpbase = "http://www.alvestrand.no/objectid";
$dirbase = "/home/httpd/html/alvestrand/objectid";
$ENV{"PATH"} = "/bin";

chdir("$dirbase")
        || die "Unable to change directory\n";
open(LOG, ">>debuglog") || die "Unable to open debuglog\n";
$date = `date`;
print LOG "Script started at $date";
print LOG "Argv is ", join(" ", @ARGV), "\n";
print LOG "Query string is $ENV{'QUERY_STRING'}\n";
#read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
#print LOG "Stdin($ENV{'CONTENT_LENGTH'}) is $buffer\n";

@pairs = split(/&/, $ENV{'QUERY_STRING'});
foreach $pair (@pairs)
{
    ($name, $value) = split(/=/, $pair);
    $value =~ tr/+/ /;
    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
    $entry{$name} = $value;
}
$expr = $entry{"text"};
if ($expr =~ /^([-A-Z0-9a-z \.\*]+)$/) {
    $expr = $1;
} else {
    die "Attempt to search for $expr - should fail!\n";
}
$prefix = $entry{"prefix"};
if ($prefix =~ /^([0-9\.]+)$/) {
   $fileprefix = "$1*.html";
} elsif (!$prefix || $prefix eq "top") {
   $fileprefix = "[0-9]*.html"; # Only search files starting with number
} else {
   die "Attempt to search under prefix $prefix\n";
}
print LOG "Action is grep -i -l -e '$expr' $fileprefix\n";
@files = `grep -i -l -e '$expr' $fileprefix`;
print LOG "Files are ", join(" ", @files), "\n";

print <<EoF;
Content-type: text/html

<html>
<head>
<title>Search result when searching for $expr under $prefix</title>
</head>
<body bgcolor=white>
<h1>Search result when searching for "$expr"</h1>
NOTE: This search mechanism is EXTREMELY primitive. Searching is without
regards to word boundaries, and searches both markup syntax and OID
contents.
<p>
<form action="/cgi-bin/hta/oidwordsearch">
<table>
<tr><td>Search again for
<td><input name="text" value="$expr"><br>
<tr><td>under prefix
<td><input name="prefix" value="$prefix">
<tr><td><input type=submit value="Search...">
</table>
</form>
<p>
<h2>The following OIDs matched</h2>
<ul>
EoF
if ($#files >= 0) {
    for $file (@files) {
	($oid = $file) =~ s/.html$//;
	$title = &gettitle($file);
	print "<li><a href=$httpbase/$file>$oid</a> - $title\n";
    }
} else {
    print "---no matches found---\n";
}

print <<EoF;
</ul>
<hr>
<a href="/objectid/top.html">Return to top of OID tree</a>
</body>
</html>
EoF

sub gettitle {
    local($file) = @_;
    open(FF, $file) || die "Unable to open $file\n";
    while (<FF>) {
        if (/<h1>(.*)<\/h1>/i) { 
            $title = $1;
            last;
        }
    }
    close FF;
    if (!$title) {
        $title = "No title";
    } elsif ($title =~ /^OID description for [\d\.]+$/) {
        $title = "Titled with OID";
    } else {
        $title =~ s/^[\d+\.]+ - //; # Take away std leading text
    }
    $title;
}
