#!/usr/bin/perl

$_= $ENV{'SCRIPT_FILENAME'};
defined $_ or $_= $0;

sub fail ($) {
    print "Content-Type: text/plain\n\nERROR\n$_[0]\n" or die $!;
    exit 0;
}

for (;;) {
    lstat $_ or fail("lstat $_ $!");
    last unless -l _;
    defined($rl= readlink) or fail("readlink $_ $!");
    if ($rl =~ m,^/,) {
	$_= $rl;
    } else {
	s,/[^/]+$,/$rl, or fail("linksub $_ ?");
    }
}
s,/[^/]+$,/helpinfos, or die "$_ ?";

open HI, "< $_" or die $?;

$tc= '-+._0-9a-z';
##$sf= $ENV{'SCRIPT_NAME'};
$sf = "/help";

while (<HI>) {
    s/\s+$//;
    if (m/^\:([$tc]*)$/) {
	$topic= $1;
    } elsif (m/^\#/) {
    } elsif (m/^\:\:(\w+)\s*(.*)$/) {
	$config{$1}= $2;
    } elsif (m/^$/) {
	undef $topic;
    } else {
	fail("notopic") unless defined $topic;
	$_= "_$_";
	s/\&/&amp;/g;
	s/\</&lt;/g;
	s/\>/&gt;/g;
	s#([^\\])\!\$([$tc]+)#
	   $1."<A href=\"$sf\">".$2."</A>";
	#ge;
	s#([^\\])\!([$tc]+)#
	   $xrefs{$topic}{$2}++;
	   $1."<A href=\"$sf/$2\">".$2."</A>";
	#ge;
	s/\\(.)/$1/g;
	s/^_//;
	$lines{$topic} .= "$_\n";
    }
}

fail("intopic") if defined $topic;

close HI or fail("close hi $!");

foreach $topic (keys %xrefs) {
    foreach $xr (keys %{ $xrefs{$topic} }) {
	defined $lines{$xr} or fail("$topic -> $xr");
    }
}

$topic= $ENV{'PATH_INFO'};
$topic =~ s,.*/,,;

fail("unknown topic") unless $topic eq 'ALL' || defined $lines{$topic};

$o= <<END;
Content-Type: text/html

<html><head>
<title>$config{'wwwtitle'}
END

$o .= "- $topic" if length $topic;
$o .= <<END;
</title>
</head><body>
END

if ($topic eq 'ALL') {
    $o.= "<h1>All help topics in alphabetical order</h1>\n";
    foreach $pt (sort keys %lines) {
	printout($pt);
    }
} else {
    $o.= "<h1>".ptitle($topic)." and its cross-references</h1>\n";
    printout($topic);
    foreach $xr (sort keys %{ $xrefs{$topic} }) {
	printout($xr) unless $xr eq $topic;
    }
    if (length $topic) {
	$o .= "See <A href=\"$sf\">top level</A>.\n";
    }
    $o .= "See <A href=\"$sf/ALL\">all topics</A>.\n<hr>\n"
}

$o.= "<address>$config{'wwwaddress'}</address>\n";
$o.= "</body></html>\n";

print $o or die $!;

sub ptitle ($) { length $_[0] ? $_[0] : 'top level'; }

sub printout ($) {
    my ($pt) = @_;
    my ($title,$rurl);
    $title= ptitle($pt);
    $rurl= length $pt ? "$sf/$pt" : $sf;
    $o .= '<h2>';
    if ($pt eq $topic) {
	$o .= $title;
    } else {
	$o .= "<A href=\"$rurl\">$title</A>";
    }
    $o .= "</h2>\n<pre>\n";
    $o .= $lines{$pt};
    $o .= "</pre>\n<hr>\n";
}
