#!/usr/bin/perl

use strict;
use warnings;

use lib '/usr/share/wml';
use lib '/usr/lib/x86_64-linux-gnu/wml';

use TheWML::Config ();

##
##  WMd -- Website META Language Documentation Browser
##
##  Copyright (c) 1996-2001 Ralf S. Engelschall.
##  Copyright (c) 1999-2001 Denis Barbier.
##
##  This program is free software; you can redistribute it and/or modify
##  it under the terms of the GNU General Public License as published by
##  the Free Software Foundation; either version 2 of the License, or
##  (at your option) any later version.
##
##  This program is distributed in the hope that it will be useful,
##  but WITHOUT ANY WARRANTY; without even the implied warranty of
##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##  GNU General Public License for more details.
##
##  You should have received a copy of the GNU General Public License
##  along with this program; if not, write to
##
##      Free Software Foundation, Inc.
##      59 Temple Place - Suite 330
##      Boston, MA  02111-1307, USA
##
##  Notice, that ``free software'' addresses the fact that this program
##  is __distributed__ under the term of the GNU General Public License
##  and because of this, it can be redistributed and modified under the
##  conditions of this license, but the software remains __copyrighted__
##  by the author. Don't intermix this with the general meaning of
##  Public Domain software or such a derivated distribution label.
##
##  The author reserves the right to distribute following releases of
##  this program under different conditions or license agreements.
##

use 5.010;

our $VERSION = TheWML::Config::_VERSION();

use Getopt::Long 2.13 ();

##
##  PROCESS ARGUMENT LINE
##
our $opt_V = -1;
our $opt_h = 0;

sub usage
{
    my ($progname) = @_;
    my ($o);

    print STDERR "Usage: $progname [options] [path ...]\n";
    print STDERR "\n";
    print STDERR "Giving Feedback:\n";
    print STDERR
        "  -V, --version[=NUM]    display version and build information\n";
    print STDERR "  -h, --help             display this usage summary\n";
    print STDERR "\n";
    exit(1);
}

sub version
{
    system("wml -V$opt_V");
    exit(0);
}

sub _process_options
{
    $Getopt::Long::bundling      = 1;
    $Getopt::Long::getopt_compat = 0;
    $SIG{'__WARN__'}             = sub {
        print STDERR "WMd:Error: $_[0]";
    };
    if ( not Getopt::Long::GetOptions( "V|version:i", "h|help" ) )
    {
        print STDERR "Try `$0 --help' for more information.\n";
        exit(0);
    }
    usage($0) if ($opt_h);
    $SIG{'__WARN__'} = undef;
}
_process_options();

#   fix the version level
if ( $opt_V == 0 )
{
    $opt_V = 1;    # Getopt::Long sets 0 if -V only
}
if ( $opt_V == -1 )
{
    $opt_V = 0;    # we operate with 0 for not set
}
version() if ($opt_V);

my $libdir  = TheWML::Config::libdir();
my $datadir = TheWML::Config::datadir();
##
##  This variable eases port on some OS.  For instance if htmlclean is
##  part of your system, you do not want to include it within WML.
##  When defining
##     %map = ('wml_aux_htmlclean' => 'htmlclean');
##  the `wml_aux_htmlclean' entry in WMd will display the htmlclean
##  manpage.
##  By default there is no mapping
my %map = ();
if ( -r "$datadir/data/wmd.map" )
{
    if ( open( MAP, "<", "$datadir/data/wmd.map" ) )
    {
        while (<MAP>)
        {
            s/^\s*(.*?)\s*=\s*(.*?)\s*$/$map{$1} = $2/e;
        }
        close(MAP);
    }
}

##
##  Find browser
##

my $browser      = $libdir . '/exec/wml_aux_iselect';
my $browser_file = TheWML::Config::datadir() . '/data/wmd.txt';
my $mandir       = TheWML::Config::mandir();

my $reader_man = qq#MANPATH="$mandir:\$MANPATH"; export MANPATH; man#;

my $reader_url   = '';
my @reader_progs = qw(w3m lynx);
WWW_PROG: foreach my $prog (@reader_progs)
{
    foreach my $dir ( split( /:/, $ENV{'PATH'} ) )
    {
        if ( -x "$dir/$prog" )
        {
            $reader_url = "$dir/$prog";
            last WWW_PROG;
        }
    }
}

my $p = 10;
while (1)
{
    my $rc =
`$browser -n "Website META Language" -t "Documentation Browser" -p$p -P <$browser_file`;
    last if ( $rc eq '' );
    $rc =~ m|^(\d+):(.*)|;
    ( $p, my $line ) = ( $1, $2 );
    if ( ( my ( $page, $sec ) = $line =~ m|^\s*(\S+)\((\d)\)\s+| ) )
    {
        if ( exists $map{$page} )
        {
            $page = $map{$page};
        }
        system("$reader_man $page");
        system("$reader_man wmd_missing") if $?;
    }
    elsif ( my ($url) = ( $line =~ m/^\s*((?:http|ftp):\/\/\S+)/ ) )
    {
        if ($reader_url)
        {
            system("$reader_url $url");
        }
        else
        {
            print STDERR "wmd:Error:  cannot access URL $url\n";
            print STDERR
                "wmd:Reason: require one of the following programs in \$PATH: "
                . join( ' ', @reader_progs ) . "\n";
            sleep(4);
        }
    }
    elsif ( my ($keyword) = ( $line =~ m/^\s*search=(.+)$/ ) )
    {
        my @L = glob("$mandir/*/wml* $mandir/*/wm[bdku]\.[1-9]*");
        my %F = ();
        foreach my $f (@L)
        {
            my $n = $f;
            $n =~
s%^.+?/(wm[bdklu](?:[:_].+?|))\.([1-9])(?:\.Z|\.z|\.gz|)$%$1($2)%;
            my $metacat = 'cat';
            $metacat = 'gzip -d -c' if ( $f =~ m/\.(?:Z|z|gz)$/ );
            my @R = `$metacat $f | grep -i '$keyword'`;
            $F{$n} += @R;
        }
        my $L = '';
        $L .= "'' 'Keyword Search Result: $keyword' '' ";
        foreach my $f ( sort { $F{$b} <=> $F{$a} } ( keys(%F) ) )
        {
            $L .= sprintf( "'%-30s (%3d) <s>' ", $f, $F{$f} );
        }
        my $p2 = 4;
        while (1)
        {
            $rc =
`$browser -n "Website META Language" -t "Documentation Browser (Keyword Search)" -p$p2 -P $L`;
            last if ( $rc eq '' );
            $rc =~ m|^(\d+):(.*)|;
            ( $p2, my $line ) = ( $1, $2 );
            if ( ( my ( $page, $sec ) = $line =~ m|^\s*(\S+)\((\d)\)\s+| ) )
            {
                system("$reader_man $page");
            }
        }
    }
}

#   exit gracefully
exit(0);

##EOF##
__END__

=head1 NAME

WMd - Website META Language Documentation Browser

=head1 VERSION

2.32.0

=head1 SYNOPSIS

B<wmd>
[B<-V>]
[B<-h>]

=head1 DESCRIPTION

This is the documentation browsing frontend to the I<Website META Language>
(WML), a free HTML generation toolkit for Unix.  See wml(1) for more details
on WML.  This frontend uses the Curses-based tool iSelect to provide an
interactive full-screen selection of all available WML manual pages.  Use this
program for quick access to the documentation from within your shell session
while working with WML.

=head1 OPTIONS

=over 4

=item B<-V>, B<--version>

Gives the version identification string of WMd. Use this to determine the
version of a installed WML toolkit.

=item B<-h>, B<--help>

Prints the usage summary page.

=back

=head1 AUTHOR

 Ralf S. Engelschall
 rse@engelschall.com
 www.engelschall.com

=head1 SEE ALSO

wml(1)

=cut

# vim: ft=perl
