#!/usr/bin/perl

=pod

=head1 NAME

inline2test - The Test::Inline 2 Test Compiler

=head1 SYNOPIS

  > inline2test ./inline2test.conf
  
  # In your inline2test.conf
  input=lib
  output=t
  execute=0
  verbose=1
  header=inline2text.txt

=head1 DESCRIPTION

C<inline2test> is the L<Test::Inline> 2 test compiler.

It's job is to scan through an arbitrary tree of Perl source code files,
locate inline test sections, extract them, convert them to test scripts,
and write them to an output path.

=cut

use strict;
use warnings;
use File::Spec::Functions ':ALL';
use Getopt::Long;
use Config::Tiny;
use Test::Inline;
use File::Slurp ();

use vars qw{$VERSION};
BEGIN {
	$VERSION = '2.099_01';
}

# Predeclare things
sub stop ($);





#####################################################################
# Process Options, Input and Config

my $execute = '';
my $changed = '';
my $verbose = '';
my $rv = GetOptions(
	execute => \$execute,
	changed => \$changed,
	verbose => \$verbose,
	);
exit(0) unless $rv;

# Get the config file
my $config = shift @ARGV
	or stop("You did not provide a config file");
my $Config = Config::Tiny->read($config)
	or stop("Failed to load config file");
my $args = $Config->{_}
	or stop("No config entries found");

# Add any forced options
$args->{execute} = 1 if $execute;
$args->{changed} = 1 if $changed;
$args->{verbose} = 1 if $verbose;

# Check some stuff
unless ( $args->{output} ) {
	stop "No output path specified";
}





#####################################################################
# Generate the Test Scripts

my $Inline = Test::Inline->new( $args )
	or stop "Error creating Test::Inline object";
if ( $args->{input} ) {
	unless ( defined $Inline->add( $args->{input} ) ) {
		stop "Error during ->add('$args->{input}') call";
	}
} else {
	unless ( defined $Inline->add_all ) {
		stop "Error during ->add_all()";
	}
}
unless ( defined $Inline->save ) {
	stop "Error while saving scripts";
}

exit(0) unless $args->{execute};





#####################################################################
# Execute Scripts

my $schedule = $Inline->schedule;
unless ( defined $schedule ) {
	stop "Error getting schedule to execute scripts";
}
unless ( $schedule ) {
	stop "Nothing to execute";
}

eval "use ExtUtils::Command::MM;";
die $@ if $@;

@ARGV = map { catfile($args->{output}, $_) } @$schedule;
test_harness(0);






#####################################################################
# Support Functions

sub stop ($) {
	print "$_[0]\n";
	exit(1);
}
