#!/usr/bin/env perl

=pod

=head1 NAME

wrt-render-all - utility for rendering static HTML files from wrt entries

=head1 USAGE

    wrt render-all
    wrt render-all --config ./wrt.json ...
    wrt render-all --help

=head1 DESCRIPTION

Renders all entries in the current wrt archive to the C<publish_dir> specified
in the configuration file (normally F<wrt.json>).  By default, this is
F<./public>.

Detailed documentation can be found in the L<App::WRT> man page or at
L<https://code.p1k3.com/gitea/brennen/wrt>.

=head1 LICENSE

    wrt 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.

=head1 AUTHOR

Brennen Bearnes <code@p1k3.com>

=cut

use 5.10.0;

use strict;
use warnings;
no  warnings 'uninitialized';

use Getopt::Long;
use Pod::Usage;
use App::WRT;
use App::WRT::FileIO;
use App::WRT::Renderer;

# If invoked directly from the command-line, caller() will return undef.
# Execute main() with a callback to print output directly, a FileIO object,
# and a copy of our real @ARGV:
if (not caller()) {
  my $output = sub { say @_; };
  my $io = App::WRT::FileIO->new();
  main($output, $io, @ARGV);
  exit(0);
}

# main() takes an output callback, a FileIO object or equivalent, and an @ARGV
# to pass in to GetOptionsFromArray().  This allows relatively simple
# integration tests to be written.  See also: t/bin-wrt-render-all.t
sub main {
  my ($output, $io, @local_argv) = @_;

  # Handle options, including help generated from the POD above.  See:
  # - http://perldoc.perl.org/Getopt/Long.html#User-defined-subroutines-to-handle-options
  # - https://metacpan.org/pod/Pod::Usage
  # - http://michael.thegrebs.com/2014/06/08/Pod-Usage/
  my $config_file = 'wrt.json';
  GetOptions(
    'config=s' => \$config_file,
    help       => sub { pod2usage(0) },
  ) or pod2usage(2);

  unless (-e $config_file) {
    die "No wrt config file found.  Tried: $config_file";
  }

  my $wrt = App::WRT::new_from_file($config_file);

  # This expects a callback to handle logging output and a callback to handle
  # file writing:

  my $renderer = App::WRT::Renderer->new(
    $wrt,
    $output,
    $io
  );

  $renderer->render();
}

1;
