#!/usr/bin/env php
<?php
if (!version_compare(PHP_VERSION, PHP_VERSION, '=')) {
    fwrite(
        STDERR,
        sprintf(
            '%s declares an invalid value for PHP_VERSION.' . PHP_EOL .
            'This breaks fundamental functionality such as version_compare().' . PHP_EOL .
            'Please use a different PHP interpreter.' . PHP_EOL,

            PHP_BINARY
        )
    );

    die(1);
}

if (version_compare('7.4.0', PHP_VERSION, '>')) {
    fwrite(
        STDERR,
        sprintf(
            'This version of PHPUnit requires PHP >= 7.3.' . PHP_EOL .
            'You are using PHP %s (%s).' . PHP_EOL,
            PHP_VERSION,
            PHP_BINARY
        )
    );

    die(1);
}

foreach ([__DIR__ . '/../../../autoload.php', __DIR__ . '/../../autoload.php', __DIR__ . '/../vendor/autoload.php', __DIR__ . '/vendor/autoload.php'] as $file) {
    if (file_exists($file)) {
        define('PHPUNIT_COMPOSER_INSTALL', $file);

        break;
    }
}

unset($file);

if (!defined('PHPUNIT_COMPOSER_INSTALL')) {
    fwrite(
        STDERR,
        'You need to set up the project dependencies using Composer:' . PHP_EOL . PHP_EOL .
        '    composer install' . PHP_EOL . PHP_EOL .
        'You can learn all about Composer on https://getcomposer.org/.' . PHP_EOL
    );

    die(1);
}

require PHPUNIT_COMPOSER_INSTALL;

$endIndex = 0;
$options = getopt('c:', ['config:'], $endIndex);

if (!isset($options['c']) && !isset($options['config'])) {
    fwrite(
        STDERR,
        'You need to pass the config file path by -c {path} or --config={path}' . PHP_EOL
    );

    die(1);
}

$arguments = array_slice($argv, $endIndex);

$configPath = $options['c'] ?? $options['config'];
$result = (new \DependencyAnalysis\AnalyzerFacade())->run($configPath, $arguments);


$exitCode = 0;

if (!$result->isSuccess()) {
    $exitCode = 1;
}

exit($exitCode);
