#!/usr/bin/perl

use strict;
use warnings;
use File::Glob ':bsd_glob';

my @opts;
while( $_ = $ARGV[0], /^-/ ) {
    shift;
    last if /^--$/;
    push @opts, $_;
}

my $platform = shift;

use Cwd;
my $top = getcwd;
my $fudge;

TOP:
while ($top) {
    for ("$top/fudge",
	"$top/spec/fudge",
	"$top/t/spec/fudge",
	"$top/perl6/t/spec/fudge",
	"$top/languages/perl6/t/spec/fudge",
    ) {
	if (-f $_) {
	    $fudge = $_;
	    last TOP;
	}
    }
    $top =~ s!(.*)/(.*)!!;
}
if (not $fudge) {
    for (split(/[:;]/, $ENV{PATH})) {
	if (-f "$_/fudge") {
	    $fudge = "$_/fudge";
	    last;
	}
    }
}

print join(' ',
    map {
        my $pick;
        if ( $_ !~ m/\.$platform$/ ) {
            my $cmd = "$^X \"$fudge\" @opts $platform $_";
            chomp( $pick = `$cmd` );
            if ($?) {
                exit($? == -1 or $? & 127 ? $? : $? >> 8);
            }
        }
        defined $pick ? $pick : ();
    } map {
        bsd_glob($_)
    } @ARGV
), "\n";


