#!perl         # just to get emacs into perl mode when editing this

package doc;

use strict;
use English '-no_match_vars';
use GameConfig;
use Getopt::Long;

local $WARNING = 1;     # same as usual -w option

my $glossary = "macro-glossary.html";


sub usage {  
  die "Syntax:  gmX doc [<filename> or <macro> or <url>]
   where <filename> is an html doc in the html/ subdir.  The .html suffix
   can be left off <filename>, and both <filename> and <macro> are
   treated case-insensitively.

   The file is displayed `nicely' to you --- that is, without the html
   tags showing up, but somewhat formatted according to them.  Links
   show up as footnotes.  (It's lynx -dump piped through your pager 
   (defaulting to less if the PAGER environment variable is not set).)

   If <filename> is omitted, all the .html files in Template/html are listed.

   If <filename> is not exactly any of the available files, filename
   matching is attempted.  If a unique match is found, it is used.
   If multiple matches are found, doc displays them and exits.
   If no matches are found, doc complains and exits.

   If the argument begins with http: it is taken as a <url> and passed
   directly to lynx to deal with.

   If the argument begins with a backslash, it is taken as a <macro>.
   In this case $glossary is searched for entries which look like 
   that macro --- e.g. \\foo will tell you about \\foo, \\foobar, etc.  
   In this form doc does not display links at all.  Note that you will 
   have to protect your backslash from the shell, 
   e.g. `doc \\\\foo' to look up \\foo macros.\n";
}

Getopt::Long::config("default");
Getopt::Long::config(qw( auto_abbrev bundling require_order ));

# Perhaps we will have more options someday.
Getopt::Long::GetOptions ("help|h" => sub { die "\n" })
  or &usage;

GAME::chdir "html";
my @html = sort grep { /\.html$/ and -f } GM::contents;

my $file;
my $target = shift or die map { "\t$_\n" } map { /(.*)\.html$/ } @html;
my @lynxopt = qw( -dump -underscore );

if ($target =~ m|^\\(.*)|) {
  my $data = GM::open $glossary;
  $file = GM::path "/.gm.$PID/doc-tmp.html";
  my $tmp = GM::open ">$file";
  while (<$data>) {
    print $tmp $_ and last if /<dt>\s*\Q$target\E/io;
  }
  while (<$data>) {
    last if /<dt>/i and not /<dt>\s*\Q$target\E/io;
    print $tmp $_;
  }
  close $data;
  close $tmp;
  -z $file and die "\tNo match in $glossary\n";
  push @lynxopt, "-nolist";
}
elsif ($target =~ /^http:/i) {
  $file = $target;  # not exactly a "file," but whatever
}
else {
  my @maybe = grep /^\Q$target\E/io, @html;
  if (@maybe > 1) {
    if (my ($exact) = grep /^\Q$target\E(\.html)?$/, @maybe) {
      @maybe = ($exact);
    }
    else {
      die map { "\t$_\n" } @maybe;
    }
  }
  elsif (not @maybe) {
    die "\tNo matching html file.\n";
  }
  $file = $maybe[0];
}
my $pager = GM::pager();
print $pager GM::lynx(@lynxopt, $file);
close $pager;
