#!/usr/bin/env php
<?php
/**
 * Wrapper for all other commands
 *
 * @see       https://github.com/zendframework/zend-expressive-tooling for the canonical source repository
 * @copyright Copyright (c) 2017-2018 Zend Technologies USA Inc. (https://www.zend.com)
 * @license   https://github.com/zendframework/zend-expressive-tooling/blob/master/LICENSE.md New BSD License
 */

declare(strict_types=1);

namespace Zend\Expressive\Tooling;

use PackageVersions\Versions;
use Symfony\Component\Console\Application;

// Setup/verify autoloading
$cwd = getcwd();
if (is_dir($cwd . '/vendor')) {
    echo "Using project autoloader based on current working directory\n";
    chdir($cwd);
    require 'vendor/autoload.php';
} elseif (file_exists($a = __DIR__ . '/../../../autoload.php')) {
    echo "Using project autoloader\n";
    require $a;
} elseif (file_exists($a = __DIR__ . '/../vendor/autoload.php')) {
    echo "Using project autoloader relative to bin directory\n";
    require $a;
} elseif (file_exists($a = __DIR__ . '/../autoload.php')) {
    echo "Using project autoloader relative to vendor directory\n";
    require $a;
} else {
    fwrite(STDERR, 'Cannot locate autoloader; please run "composer install"' . PHP_EOL);
    exit(1);
}

// Some commands require a properly configured application structure in
// order to be executed. As such, we build the structure iteratively,
// adding first those that can always run, and then those that have special
// requirements.
$commandList = [
    new Factory\CreateFactoryCommand('factory:create'),
    new CreateMiddleware\CreateMiddlewareCommand('middleware:create'),
    new MigrateInteropMiddleware\MigrateInteropMiddlewareCommand('migrate:interop-middleware'),
    new MigrateMiddlewareToRequestHandler\MigrateMiddlewareToRequestHandlerCommand(
        'migrate:middleware-to-request-handler'
    ),
    new Module\CreateCommand('module:create'),
    new Module\DeregisterCommand('module:deregister'),
    new Module\RegisterCommand('module:register'),
];

if (file_exists($cwd . '/config/container.php')) {
    $commandList[] = new CreateHandler\CreateHandlerCommand('action:create');
    $commandList[] = new CreateHandler\CreateHandlerCommand('handler:create');
}

$version = strstr(Versions::getVersion('zendframework/zend-expressive-tooling'), '@', true);

$application = new Application('expressive', $version);
$application->addCommands($commandList);
$application->run();
