#!/usr/bin/env perl

use strict;
use warnings;
use autodie qw( :all );

use 5.01000;

use File::Find::Rule;
use File::pushd;
use File::Temp qw( tempdir );
use Path::Class qw( file );

my $branch = shift || 'master';

my $tempdir = tempdir( CLEANUP => 1 );

{
    my $dir = pushd($tempdir);

    system(
        'git',      'clone',
        '--branch', $branch,
        'https://github.com/houseabsolute/List-SomeUtils.git',
        'pp'
    );
}

my $t_root = "$tempdir/pp/t";

for my $file ( map { file($_) }
    File::Find::Rule->name(qr/\.(?:t|pm)$/)->in($t_root) ) {

    my $to_file = file( 't', $file =~ s{^\Q$t_root\E/}{}r );

    $to_file->dir->mkpath( 0, 0755 );

    my $content = $file->slurp;
    next if $content =~ /^\# PP only/;
    $content =~ s/PP/XS/;

    if ( $file =~ /\.t/ ) {
        my $guard = <<'EOF';
use Test::More 0.96;

BEGIN {
    eval 'require List::SomeUtils';
    if ($@) {
        plan skip_all => 'These tests require that List::SomeUtils already be installed';
    }
}
EOF

        $content =~ s/(BEGIN .+?\n)/$guard$1/;
    }

    $to_file->spew($content);
}
