#!/usr/bin/perl
# mh-book-index
# mh-book-index-frames
#
# Copyright (C) 1999  Peter S Galbraith <psg@debian.org>
# This script is licensed under the GNU GENERAL PUBLIC LICENSE Version 2
#
# This is a search engine for the mh-book Debian package.  If called as
# mh-book-index-frames it returns HTML output suitable for the frames
# version of mh-book.
#
# If you are adapting this script, say to Red Hat, then you'll want to edit
# the string /usr/share/doc/mh-book/html/ to where the book is installed on
# your system and the URL path returned.

my($string, $substring, @matches, @matchesLeft);

print "Content-type: text/html\n\n<BODY BGCOLOR=\"#FFFFFF\"><HTML>\n";
if ($0 =~ /frames/) { print "<BASE TARGET=\"main\">\n" }
if (! $ARGV[0]) {
    print '
<TITLE>Search Index for MH &amp; xmh Book</TITLE>
<H1>Search Index for MH &amp; xmh Book</H1>

<ISINDEX>

';
    if ($0 =~ /frames/) { 
        print "Enter keywords separated by a space.
I will do an AND condition on them.
<P>
" 
    } else { 
        print "Enter a word you want to search for (case insensitive).
If you type more than one word (with a space between), 
all of them will appear in each match (AND condition).
<P>
"
    }
} else {
    my $word = shift;
    if ((defined($ENV{"SERVER_NAME"})) && ($ENV{"SERVER_NAME"} ne "")) {
        $cgi = "http://" . $ENV{"SERVER_NAME"} . "/cgi-bin/";
        $url = "http://" . $ENV{"SERVER_NAME"} . "/doc/mh-book/html/";
    } else {
        $cgi = "";
        $url = "/doc/mh-book/html/";
    }
    open(INDEX, "< /usr/share/doc/mh-book/html/indx-cgi.html");
    while (<INDEX>) {
        if (/<\/I>: *([^<]+)</) {
            $string = $1;
            if ($string =~ /\b$word\b/i) {
#               s|<A HREF=\"|<A HREF=\"file:/usr/share/doc/mh-book/html/|g;
                s|<A HREF=\"|<A HREF=\"${url}|g;
                push(@matches, $_);
            }
        }
    }
    close(INDEX);
    while ($word = shift) {
        foreach $string (@matches) {
            if ($string =~ /<\/I>: *([^<]+)</) {
                $substring = $1;
                if ($substring =~ /\b$word\b/i) {
                    push(@matchesLeft, $string);
                }
            }
        }
        @matches = @matchesLeft;
        undef(@matchesLeft);
    }
    if ($#matches < 0) {
        print "<B>Sorry, no match found.</B>";
    } else {
        print "
<UL COMPACT>
<H1>MH &amp; xmh: Index Search Results</H1>
";
        foreach $string (@matches) {
            print "<LI>$string";
        }
        print "</UL>";
    }
    if ($0 =~ /frames/) {
        print "
<CENTER>
[<A TARGET=\"TOC\" HREF=\"${url}frm-toc.html\">Back to Index</A>]
</CENTER>
<P>
<HR>
<P>
";
    } else {
        print "
<CENTER>

[<A HREF=\"${cgi}mh-book-index\">Do another search</A>]       
[<A HREF=\"${url}indx-map.html.gz\">Other Indexes</A>]
[<A HREF=\"${url}toc.html.gz\">Complete Table of Contents (long)</A>]
</CENTER>
<P>
<HR>
<P>
";
    }
}
print "</BODY></HTML>\n";
undef @matches;
