#!/usr/bin/perl

# Copyright 2004-2010, Paul Johnson (pjcj@cpan.org)

# This software is free.  It is licensed under the same terms as Perl itself.

# The latest version of this software should be available from my homepage:
# http://www.pjcj.net

use strict;
use warnings;

use Getopt::Long;

my $Options =
{
    dry_run        => 0,
    ignore_failure => 0,
    silent         => 1,
    version        => [],
};

my $Silent = "";

sub get_options
{
    die "Bad option" unless
    GetOptions($Options,  # Store the options in the Options hash.
               qw(
                   dry_run!
                   ignore_failure!
                   silent!
                   version=s
                 ));
    $Options->{version} =
        [ map { ($_, "$_-thr") }
              qw( 5.6.1 5.6.2
                  5.8.0 5.8.1 5.8.2 5.8.3 5.8.4 5.8.5 5.8.6 5.8.7 5.8.8 5.8.9
                  5.10.0 5.10.1 5.11.0 5.12.0 5.12.1 5.13.0 5.13.1 5.13.2
                  5.13.3 5.13.4 ) ]
        unless @{$Options->{version}};
    $Silent = " >/dev/null 2>&1" if $Options->{silent};
    $Options->{version} =
        [ grep eval { !system "perl$_ -v$Silent" }, @{$Options->{version}} ];
    print "Testing against: @{$Options->{version}}\n";
}

sub sys
{
    my ($command, $user) = @_;
    print "$command\n";
    return if $Options->{dry_run};
    $command .= $Silent if $Options->{silent} && !$user;
    my $ret = system $command;
    die "command failed: $?" if $ret && !$Options->{ignore_failure};
}

get_options;
my $command = "@ARGV" or die "Usage: $0 [-v version] command\n";

for my $v (@{$Options->{version}})
{
    my $perl = "perl$v";
    (my $c = $command) =~ s/=perl/$perl/g;
    $c =~ s/=v/$v/g;
    sys "rm -rf t/e2e";
    sys "$perl Makefile.PL";
    sys "make clean";
    sys "$perl Makefile.PL";
    sys "make";
    if ($c eq "test")
    {
        my ($dir)   = grep -x "$_/$perl", split /:/, $ENV{PATH};
        eval
        {
            my $l = readlink "$dir/$perl";
            ($dir) = $l =~ m|(.*)/[^/]+|;
        };
        my ($prove) = grep -x,
                      map "$dir/prove$_",
                      "", $v, $v =~ /([\d.]+)/ ? $1 : "";
        if ($prove)
        {
            my $cpus = 1;
            eval { chomp ($cpus = `grep -c processor /proc/cpuinfo`); };
            $cpus-- if $cpus > 4;
            $c = "$prove -b -r -j$cpus t";
            eval { sys $c, 1 };
            next unless $@;
        }
        $c = "make test";
    }
    sys $c, 1;
}
