#!/usr/bin/env php
<?php

chdir(__DIR__ . '/../');

// Clean up vendor
shell_exec('rm -rf vendor');
// Make vendor with no dev requirements
shell_exec('composer install --no-dev');

$pharName = 'phpmnd.phar';

$pharFile = getcwd() . '/phpmnd.phar';

if (file_exists($pharFile)) {
    unlink($pharFile);
}
$phar = new Phar($pharFile, 0, $pharName);
$phar->addFile('bin/phpmnd');
$dirs = [
    'src',
    'vendor',
];
foreach($dirs as $dir) {
    addDir($dir, $phar);
}
$phar->setStub(
    "#!/usr/bin/env php
    <?php
    Phar::mapPhar('$pharName');
    require 'phar://$pharName/bin/phpmnd';
    __HALT_COMPILER();"
);

function addDir($dir, $phar)
{
    $code = realpath("$dir/");
    $codeLength = strlen($code);
    $directory = new RecursiveDirectoryIterator(
        $code,
        RecursiveDirectoryIterator::FOLLOW_SYMLINKS
    );
    $iterator = new RecursiveIteratorIterator(
        $directory,
        0,
        RecursiveIteratorIterator::CATCH_GET_CHILD
    );
    foreach ($iterator as $file) {
        $fullPath = $file->getPathname();
        $path = $dir . substr($fullPath, $codeLength);
        if (is_file($path)) {
            $phar->addFile($path);
        }
    }
}

