#!/usr/bin/env perl
# BEGIN BPS TAGGED BLOCK {{{
#
# COPYRIGHT:
#
# This software is Copyright (c) 1996-2024 Best Practical Solutions, LLC
#                                          <sales@bestpractical.com>
#
# (Except where explicitly superseded by other copyright notices)
#
#
# LICENSE:
#
# This work is made available to you under the terms of Version 2 of
# the GNU General Public License. A copy of that license should have
# been provided with this software, but in any event can be snarfed
# from www.gnu.org.
#
# This work 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 the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 or visit their web page on the internet at
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
#
#
# CONTRIBUTION SUBMISSION POLICY:
#
# (The following paragraph is not intended to limit the rights granted
# to you to modify and distribute this software under the terms of
# the GNU General Public License and is only of importance to you if
# you choose to contribute your changes and enhancements to the
# community by submitting them to Best Practical Solutions, LLC.)
#
# By intentionally submitting any modifications, corrections or
# derivatives to this work, or any other work intended for use with
# Request Tracker, to Best Practical Solutions, LLC, you confirm that
# you are the copyright holder for those contributions and you grant
# Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
# royalty-free, perpetual, license to use, copy, create derivative
# works based on those contributions, and sublicense and distribute
# those contributions and any derivatives thereof.
#
# END BPS TAGGED BLOCK }}}
use strict;
use warnings;

use Getopt::Long;
use File::Temp;
use File::Spec;
use File::Path qw(make_path rmtree);
use File::Copy qw(copy);
use Encode qw(decode_utf8);
use HTML::Entities qw(encode_entities);
use List::Util qw(first);
use RT::Pod::HTMLBatch;

my %opts;
GetOptions(
    \%opts,
    "help|h",
    "source=s",
    "to=s",
    "extension=s",
);

if ( $opts{'help'} ) {
    require Pod::Usage;
    print Pod::Usage::pod2usage( -verbose => 2 );
    exit;
}

die "--to=DIRECTORY is required\n"  unless $opts{to};

$opts{to} = File::Spec->rel2abs($opts{to});

make_path( $opts{to} )              unless -e $opts{to};
die "--to MUST be a directory\n"    unless -d $opts{to};

# Unpack the tarball, if that's what we're given.
my $tmpdir;
if (($opts{source} || '') =~ /\.tar\.gz$/ and -f $opts{source}) {
    $tmpdir = File::Temp->newdir();

    system("tar", "xzpf", $opts{source}, "-C", $tmpdir);
    $opts{source} = first { -d $_ } <$tmpdir/*>;

    die "Can't find directory to chdir into after unpacking tarball"
        unless $opts{source};
}
chdir $opts{source} if $opts{source};

my @dirs = (
    qw(
        docs
        etc
        lib
        bin
        sbin
        devel/tools
        local/lib
        local/sbin
        local/bin
    ),
    glob("local/plugins/*/{lib,sbin,bin}"),
    glob("docs/UPGRADING*"),
);

my $converter = RT::Pod::HTMLBatch->new;

sub generate_configure_help {
    my $configure = shift;
    my $help = `./$configure --help`;
    my $dest = "$opts{to}/configure.html";

    if ($help and open my $html, ">", $dest) {
        print $html join "\n",
            "<pre>", encode_entities($help), "</pre>", "\n";
        close $html;
        $converter->note_for_contents_file(["configure options"], $configure, $dest);
    } else {
        warn "Can't open $dest: $!";
    }
}

# Generate a page for ./configure --help if we can
if (-x "configure.ac" and -d ".git") {
    rmtree("autom4te.cache") if -d "autom4te.cache";
    generate_configure_help("configure.ac");
}
elsif (-x "configure") {
    generate_configure_help("configure");
}
else {
    warn "Unable to generate a page for ./configure --help!\n"
        unless $opts{extension};
}

# Manually "convert" README* and 3.8-era UPGRADING* to HTML and push them into
# the known contents.
for my $file (<README* UPGRADING*>) {
    (my $name = $file) =~ s{^.+/}{};

    my $str = "";

    if ( $name =~ s/\.md$// ) {
        require Markdown::Render;
        my $md = Markdown::Render->new( infile => $file );
        $str = $md->render_markdown->get_html;
        $str =~ s{\bdocs/images/}{images/}g;
        $str = qq{<div class="rt-markdown">$str</div>};
    }
    else {
        open my $source, "<", $file
            or warn "Can't open $file: $!", next;

        $str .= encode_entities( decode_utf8($_) ) while <$source>;
        close $source;

        $str = "<pre>$str</pre>";
        $str =~ s{\bdocs/([a-z_/-]+)\.pod\b}{<a href="$1.html">docs/$1.pod</a>}ig;
        $str =~ s{\betc/(RT_Config)\.pm\b}{<a href="$1.html">etc/$1.pm</a>}g;
        $str =~ s{\betc/(UPRGADING\.mysql)\b}{<a href="$1.html">etc/$1</a>}g;
        $str =~ s{\b(https?://(?!rt\.example\.com)[.a-z0-9/_:-]+(?<!\.))}{<a href="$1">$1</a>}ig;
        $str =~ s{\b([\w-]+\@(lists\.)?bestpractical.com)\b}{<a href="mailto:$1">$1</a>}g;
    }

    my $dest = "$opts{to}/$name.html";
    open my $html, ">", $dest
        or warn "Can't open $dest: $!", next;
    print $html $str;
    close $html;

    $converter->note_for_contents_file([$name], $file, $dest);
}

# Copy images into place
make_path("$opts{to}/images/");
copy($_, "$opts{to}/images/")
    for <docs/images/*.{png,jpeg,jpg,gif}>;

# Temporarily set executable bits on upgrading doc to work around
# Pod::Simple::Search limitation/bug:
#    https://rt.cpan.org/Ticket/Display.html?id=80082
sub system_chmod {
    system("chmod", @_) == 0
        or die "Unable to chmod: $! (exit $?)";
}
system_chmod("+x", $_) for <docs/UPGRADING*>;

# Convert each POD file to HTML
$converter->batch_convert( \@dirs, $opts{to} );

# Run it again to make sure local links are linked correctly
$converter->contents_file(undef);
$converter->batch_convert( \@dirs, $opts{to} );

# Remove execution bit from workaround above
system_chmod("-x", $_) for <docs/UPGRADING*>;

# Need to chdir back out, if we are in the tmpdir, to let it clean up
chdir "/" if $tmpdir;

exit 0;

__END__

=head1 NAME

rt-static-docs - generate doc shipped with RT

=head1 SYNOPSIS

    rt-static-docs --to /path/to/output [--source /path/to/rt]

=head1 DESCRIPTION

RT ships with documentation (written in POD) embedded in library files, at the
end of utility scripts, and in standalone files.  This script finds all of that
documentation, collects and converts it into a nice set of HTML files, and tops
it off with a helpful index.

Best Practical uses this to publish documentation under
L<http://bestpractical.com/rt/docs/>.

=head1 OPTIONS

=over

=item --to

Set the destination directory for the output files.

=item --source

Set the RT base directory to search under.  Defaults to the current working
directory, which is fine if you're running this script as
C<devel/tools/rt-static-docs>.

May also point to a tarball (a file ending in C<.tar.gz>) which will be
unpacked into a temporary directory and used as the RT base directory.

=item --extension=RTx::Foo

Indicates when C<--source> is an RT extension, such as RT::IR.  Takes an
extension name for future use, but currently it only acts as a flag to suppress
a warning about not finding ./configure.

=item --help

Print this help.

=back

=cut
