#!/usr/bin/env perl

use strict;
use warnings;

use feature 'say';

use File::Basename;
use File::Find;
use File::Spec::Functions;
use Getopt::Long;

use File::Path 'make_path';

sub options {
  my $data = {};

  GetOptions(
    "help|h" => \$data->{help},
    "input|i=s" => \$data->{input},
    "output|o=s" => \$data->{output},
    "pattern|p=s" => \$data->{pattern},
    "template|t=s" => \$data->{template},
  );

  return $data;
}

sub helptext {
  my ($self) = @_;

  return join "\n", "testauto [options]", <<"EOF";

  -h --help      Display help text.
  -t --template  Filepath for POD template.
  -p --pattern   Pattern to use to filter files.
  -o --output    Directory for .pod files.
  -i --input     Directory for .t files.

e.g. testauto -i t -o lib -t ./template.pod
EOF
}

sub main {
  my ($helptext, $options) = @_;

  require Test::Auto;

  my @files;

  if ($options->{help}) {
    say $helptext;
    exit 1;
  }

  my $input = $options->{input} || 't';
  my $output = $options->{output} || 'lib';
  my $pattern = $options->{pattern} || '.*';
  my $template = $options->{template};

  if ($template) {
    $ENV{TEST_AUTO_TEMPLATE} = $template;
  }

  find sub {
    push @files, $File::Find::name if -f && /\.t$/
  }, $input;

  for my $file (sort grep /$pattern/, @files) {
    my $test = Test::Auto->new($file);
    my $parser = $test->parser;
    my $package = $parser->render('name');

    my $podfile = $package;
       $podfile =~ s/::/\//g;
       $podfile = catfile($output, "$podfile.pod");

    make_path(dirname($podfile));

    open my $fh, '>', $podfile or die "Error writing POD file, $!: $podfile";
    print $fh $test->document->render;
    close $fh;

    say "Created $podfile";
  }

  return;
}

main(helptext(), options());

=encoding utf8

=head1 NAME

testauto

=cut

=head1 ABSTRACT

Generate POD from Tests

=cut

=head1 SYNOPSIS

  testauto -i t -o lib -t ./mytemplate

=cut

=head1 DESCRIPTION

This tool lets you generate POD documents from test files that adhere to the
specification, L<Test::Auto/SPECIFICATION>.

=cut

=head1 OPTIONS

  -h --help      Display help text.
  -t --template  Filepath for POD template.
  -p --pattern   Pattern to use to filter files.
  -o --output    Directory for .pod files.
  -i --input     Directory for .t files.

=cut

=head1 AUTHOR

Al Newkirk, C<awncorp@cpan.org>

=head1 LICENSE

Copyright (C) 2011-2019, Al Newkirk, et al.

This is free software; you can redistribute it and/or modify it under the terms
of the The Apache License, Version 2.0, as elucidated in the
L<"license file"|https://github.com/iamalnewkirk/test-auto/blob/master/LICENSE>.

=head1 PROJECT

L<Wiki|https://github.com/iamalnewkirk/test-auto/wiki>

L<Project|https://github.com/iamalnewkirk/test-auto>

L<Initiatives|https://github.com/iamalnewkirk/test-auto/projects>

L<Milestones|https://github.com/iamalnewkirk/test-auto/milestones>

L<Issues|https://github.com/iamalnewkirk/test-auto/issues>

=cut
