#!/usr/local/bin/perl -w

use strict;
use Data::Dumper;
use Test::Harness;
$Test::Harness::verbose = shift if defined $ARGV[0] and $ARGV[0] =~ /^\d+$/ || $ARGV[0] eq "-v";

my $formatter;
if (@ARGV && $ARGV[0] =~ /^--formatter=/) {
    (undef, $formatter) = split(/=/, shift, 2);
    $formatter = "TAP::Formatter::$formatter" unless $formatter =~ /::/
}

unshift(@INC, "blib/lib", "blib/arch");

my @tests;
if (@ARGV) {
    for (@ARGV) {
        if (-d $_) {
            push(@tests, <$_/*.t>);
        }
        else {
            $_ .= ".t" unless /\.t$/;
            push(@tests, $_);
        }
    }
}
else {
    @tests = (<t/*.t>);
}

if ($formatter) {
    use File::Path;
    File::Path::rmtree("tap");

    $ENV{PERL_TEST_HARNESS_DUMP_TAP} = "tap";

    require TAP::Harness;

    my $harness = TAP::Harness->new({
        formatter_class => $formatter,
        merge           => 1,
        timer           => 1,
        lib             => \@INC,
        exec            => ['/usr/bin/perl', "-T", '-MDevel::Cover=-silent,1']
    });

    my $result = $harness->runtests(@tests);

    my $return_code = $result->{'exit'};

    # make sure we return with the exit code of the tests so if we fail we bubble it up
    exit($return_code);

}
else {
    runtests @tests;
}
