#!/usr/bin/env php
<?php
/* (c) Anton Medvedev <anton@medv.io>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
if (ini_get('phar.readonly') === '1') {
    fwrite(STDERR, "Writing to phar files is disabled. Change your `php.ini` or use `-d phar.readonly=false`.\n");
    exit(1);
}

define('__ROOT__', realpath(__DIR__ . '/..'));
chdir(__ROOT__);

$opt = getopt('v:', ['nozip']);

$version = $opt['v'] ?? null;
if (empty($version)) {
    fwrite(STDERR, "Please, specify version as \"-v8.0.0\".\n");
    exit(1);
}
if (!preg_match('/^\d+\.\d+\.\d+(-\w+(\.\d+)?)?$/', $version)) {
    fwrite(STDERR, "Version must be \"7.0.0-beta.42\". Got \"$version\".\n");
    exit(1);
}

passthru('composer install --no-dev --prefer-dist --optimize-autoloader');

$pharName = "deployer.phar";
$pharFile = __ROOT__ . '/' . $pharName;
if (file_exists($pharFile)) {
    unlink($pharFile);
}

$ignore = [
    '.anton',
    '.git',
    'Tests',
    'tests',
    'deploy.php',
    '.php-cs-fixer.dist.php',
];

$compress = !isset($opt['nozip']);

$phar = new Phar($pharFile, 0, $pharName);
$phar->setSignatureAlgorithm(Phar::SHA256);
$phar->startBuffering();

$iterator = new RecursiveDirectoryIterator(__ROOT__, FilesystemIterator::SKIP_DOTS);
$iterator = new RecursiveCallbackFilterIterator($iterator,
    fn(SplFileInfo $fileInfo) => !in_array($fileInfo->getBasename(), $ignore, true),
);
$iterator = new RecursiveIteratorIterator($iterator);
$iterator = new CallbackFilterIterator($iterator,
    // 'bash', 'fish', 'zsh' are completion templates
    fn(SplFileInfo $fileInfo) => in_array($fileInfo->getExtension(), ['php', 'exe', 'bash', 'fish', 'zsh'], true),
);

foreach ($iterator as $fileInfo) {
    $file = str_replace(__ROOT__, '', $fileInfo->getRealPath());
    echo "+ $file\n";
    $phar->addFile($fileInfo->getRealPath(), $file);

    if ($compress) {
        $phar[$file]->compress(Phar::GZ);
        if (!$phar[$file]->isCompressed()) {
            fwrite(STDERR, "Could not compress: $file\n");
        }
    }
}

// Add non-PHP files that the iterator skips.
foreach ([
    '/recipe/provision/Caddyfile',
    '/recipe/provision/404.html',
] as $extra) {
    echo "+ $extra\n";
    $phar->addFile(realpath(__ROOT__ . $extra), $extra);
}

// Add bin/dep with version baked in.
echo "+ /bin/dep\n";
$depContent = file_get_contents(__ROOT__ . '/bin/dep');
$depContent = str_replace("#!/usr/bin/env php\n", '', $depContent);
$depContent = str_replace('__FILE__', 'str_replace("phar://", "", Phar::running())', $depContent);
$depContent = preg_replace("/run\('.+?'/", "run('$version'", $depContent);
$phar->addFromString('bin/dep', $depContent);

$phar->setStub(<<<STUB
    #!/usr/bin/env php
    <?php
    Phar::mapPhar('{$pharName}');
    require 'phar://{$pharName}/bin/dep';
    __HALT_COMPILER();
    STUB);
$phar->stopBuffering();
unset($phar);

echo "$pharName was created successfully.\n";
