#!/usr/bin/perl

# pod2test - Generate test scripts for a tree of modules

# Note to testers, this is a half-assed hack job. It needs to be
# changed to closer match the old pod2test.

use strict;
use Getopt::Long ();
use File::Slurp ();
use Test::Inline2 ();
use File::Find::Rule ();
use constant FFR => 'File::Find::Rule';

# Get options
my $init = '';
Getopt::Long::GetOptions( 'init=s' => \$init );

# Load the initialisation code
if ( $init ) {
	error("Initialisation file '$init' does not exist") unless -f $init;
	error("No permissions on initialisation file '$init'") unless -f $init;
	$init = File::Slurp::read_file( $init );
	$init =~ s/(?:\015{1,2}\012|\015|\012)/\n/g;
}

# Input directory
my $input  = shift @ARGV;
error("Input directory does not exist") unless -d $input;
error("No permissions on input directory") unless -r $input;
error("No permissions on input directory") unless -x $input;

# Output directory	
my $output = shift @ARGV;
error("Output directory does not exist") unless -d $output;
error("No permissions on output directory") unless -w $output;
error("No permissions on output directory") unless -x $output;

# Create the Test::Inline2 object
my $Inline = Test::Inline2->new(
	verbose => 1,
	output  => $output,
	$init ? (file_content => \&file_content) : (),
	) or die "Failed to create Test::Inline2 object";

# Find all the modules to add
my $Rule = FFR->file->name('*.pm');
my @files = $Rule->in( $input ) or error("No .pm files found to add");
print "Found " . scalar(@files) . " file(s) to check for tests in\n";

foreach my $file ( @files ) {
	unless ( defined $Inline->add( $file ) ) {
		error("Failed to add '$file'");
	}
}

# Generate and save the files
$Inline->save or error("Failed to generate and save test files");

print "Done\n\n";

exit(0);

# A replacement file_content for when we want to add init content
sub file_content {
	my ($Inline, $File) = @_;

	# Get the merged content
	my $content = $File->merged_content;
	return undef unless defined $content;

	# Determine a plan
	my $tests = $File->tests;
	my $plan  = defined $tests
		? "tests => $tests"
		: "'no_plan'";

	# Wrap the merged contents with the rest of the test
	# file infrastructure.
	my $file = <<"END_TEST";
#!/usr/bin/perl -w

use strict;
use Test::More $plan;
\$| = 1;

# Common initialisation
$init


$content



1;
END_TEST

	$file;
}




sub error {
	my $message = shift;
	print "\nError: $message\n";
	exit(1);
}
