#!/usr/bin/env perl -w
use strict;
use warnings;
use Config;
use TAP::Harness::Archive;
use Data::Dumper;
use lib 'lib';
use Math::GSL;
$|++;

my $archive = shift || 'my_test_run.tar.gz';
my $server = 'smolder.leto.net';
my $port = '8080';
my ($user,$pass) = qw/leto bessel_J0/;
my $archname = $Config{archname};
if ($archname =~ /darwin/i){
    chomp($archname = `uname -p`);
}
my $me = $^O eq 'MSWin32' ? $ENV{'USERNAME'}
        : $ENV{'LOGNAME'} || eval { getpwuid($<) };

my $domain = 'unknown';
if ($^O eq 'MSWin32') {
    $domain = $ENV{'USERDOMAIN'};
} else {
    eval { require Sys::Hostname; $domain = Sys::Hostname::hostname(); };
}

my ($git_id,$git_branch) = ('','');

if ( -e '.git' ) {
    chomp($git_id = `git log -p -n 1|grep commit`);
    $git_id =~ s/commit //;
    chomp($git_branch = `git branch | grep "^\*"`);
    $git_branch =~ s/\* //;
}
my $properties = {
    'Math::GSL'     => $Math::GSL::VERSION,
    'Git Commit'    => $git_id,
    'Git Branch'    => $git_branch,
    'Submitter'     => "$me\@$domain",
    'Perl Version'  => $Config{version},
    'Config Args'   => $Config{config_args},
    'CC Flags'      => $Config{ccflags},
    'Double Size'   => $Config{doublesize},
    'Long Doubles'  => $Config{uselongdouble},
    'Multiplicity'  => $Config{usemultiplicity},
    '64bit ints'    => $Config{use64bitint},
    '64bit all'     => $Config{use64bitall},
    'Patch level'   => $Config{version_patchlevel_string},
    'Perl @INC'     => join(":",@INC),
    'PERL5LIB'      => $ENV{PERL5LIB},
};
my @files = glob('t/*.t');
my %options = (
           verbosity        => 0,
           jobs             => 2,
           merge            => 1,
           lib              => [ 'lib', 'blib/lib', 'blib/arch' ],
           archive          => $archive,
           extra_properties => $properties,
           extra_files      => [ ],
);


my $harness = TAP::Harness::Archive->new(\%options);
$harness->runtests(@files);
my $cmd =<<CMD;
smolder_smoke_signal --server $server --port $port \\
    --username '$user' --password '$pass' --file $archive --project Math::GSL \\
    --platform $Config{osname} --architecture $archname --tags "\$USER , $Config{osname}, Math::GSL $Math::GSL::VERSION, $git_branch, Perl $Config{version}"
CMD
print "about to do:\n$cmd\n";

system $cmd;

if ($? == -1) {
    print "failed to execute: $!\n";
} elsif ($? & 127) {
    printf "smolder_smoke_signal died with signal %d, %s coredump\n", ($? & 127),  ($? & 128) ? 'with' : 'without';
} else {
    printf "smolder_smoke_signal exited with value %d\n", $? >> 8;
}
