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

use HHIT\ConfigGenerator\Command\GenerateConfigsCommand;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;

if (!in_array(PHP_SAPI, ['cli', 'phpdbg', 'embed'], true)) {
    echo 'Warning: The console should be invoked via the CLI version of PHP, not the '.PHP_SAPI.' SAPI'.PHP_EOL;
}

set_time_limit(0);

$candidates = [
    dirname(__DIR__) . '/../../autoload.php' => dirname(__DIR__) . '/../../../',
    dirname(__DIR__) . '/vendor/autoload.php' => dirname(__DIR__)
];

$autoloaderPath = null;
$projectDir = null;
foreach ($candidates as $autoloaderPathCandidate => $projectDirCandidate) {
    if (file_exists($autoloaderPathCandidate)) {
        $autoloaderPath = $autoloaderPathCandidate;
        $projectDir = $projectDirCandidate;
        break;
    }
}
if (null === $autoloaderPath) {
    throw new RuntimeException('Unable to locate autoload.php file.');
}
require_once $autoloaderPath;
unset($candidates, $autoloaderPathCandidate, $pojectDirCandidate);

$application = new Application('Configuration Generator');
$application->add(new GenerateConfigsCommand($projectDir));

$input = new ArgvInput();
if (null !== $env = $input->getParameterOption(['--env', '-e'], 'dev', true)) {
    putenv('APP_ENV='.$_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = $env);
}

$output = new ConsoleOutput();
$application->run($input, $output);
