unit class Blin::Tester::Zef;

has $.path;
has $.binary;
has $.output-failed;
has $!zef-config-path;
has @.sources;


submethod TWEAK ( ) {

    #| Where to install zef
    my $zef-path          = â€˜data/zefâ€™.IO;
    my $zef-config-path   = â€˜data/zef-config.jsonâ€™.IO;
    my $zef-dumpster-path = â€˜data/zef-dataâ€™.IO;
    #â†‘ XXX Trash pickup services are not working, delete the directory
    note â€˜ğŸ¥� Ensuring zef checkoutâ€™;
    if $zef-path.d {
        run :cwd($zef-path), <git pull>
    } else {
        run <git clone https://github.com/ugexe/zef>, $zef-path
    }

    note â€˜ğŸ¥� Creating a config file for zefâ€™;
    {
        run(:err, $*EXECUTABLE.absolute, â€˜-Iâ€™, $zef-path, $zef-path.add(â€˜/bin/zefâ€™), â€˜--helpâ€™).err.slurp
          .match: /^^CONFIGURATION \s* (.*?)$$/;

        use JSON::Fast;
        my $zef-config = from-json $0.Str.IO.slurp;

        # Turn auto-update off
        for $zef-config<Repository>.list -> $arr {
            for @$arr {
                next unless .<module> eq â€˜Zef::Repository::Ecosystemsâ€™;
                .<options><auto-update> = 0; # XXX why is this not a boolean?
                @!sources.push(.<options><mirrors>.head);
            }
        }

        $zef-config<TempDir>  = $zef-dumpster-path.add(â€˜tmpâ€™).absolute;
        $zef-config<StoreDir> = $zef-dumpster-path.add(â€˜storeâ€™).absolute;

        spurt $zef-config-path, to-json $zef-config;

        run $*EXECUTABLE.absolute, â€˜-Iâ€™, $zef-path, $zef-path.add(â€˜/bin/zefâ€™), â€œ--config-path=$zef-config-pathâ€�, â€˜updateâ€™;

    }

    $!zef-config-path = $zef-config-path;
    $!path = $zef-path;
    $!binary = $!path.add: 'bin/zef';
    $!output-failed = '[FAIL]:';

}

method test-command( ::?CLASS:D: :$testable!, :$install-path!, :$module-name! ) {
    $!binary.absolute,
    â€œ--config-path=$!zef-config-pathâ€�,
    |<--verbose --force-build --force-install>,
    ($testable ?? â€˜--force-testâ€™ !! â€˜--/testâ€™),
    |<--/depends --/test-depends --/build-depends>,
    â€˜installâ€™,
    â€œ--to=inst#$install-pathâ€�,
    $module-name,
}
