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

use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\ErrorHandler\Debug;
use Symfony\Component\Yaml\Yaml;

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);

$possibleRootDirectories = [
    __DIR__ . '/../../../../',
    __DIR__ . '/../'
];

foreach ($possibleRootDirectories as $directory) {
    $file = $directory . 'vendor/autoload.php';
    if (file_exists($file)) {
        require $file;
        break;
    }
}

$getZikulaEnv = function(ArgvInput $input) {
    $defaultEnv = $input->getParameterOption(['--env', '-e'], getenv('APP_ENV') ?: 'dev');
    // prefer install and upgrade commands default to prod environment
    $isInstallUpgradeCommand = ((strpos($input->getFirstArgument(), 'zikula:install') !== false)
        || (strpos($input->getFirstArgument(), 'zikula:upgrade') !== false));
    $env = $isInstallUpgradeCommand ? 'prod' : $defaultEnv;

    return $env;
};

$input = new ArgvInput();
if (null !== $env = $getZikulaEnv($input)) {
    putenv('APP_ENV=' . $_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = $env);
}

if ($input->hasParameterOption('--no-debug', true)) {
    putenv('APP_DEBUG=' . $_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = '0');
}

foreach ($possibleRootDirectories as $directory) {
    $file = $directory . 'config/bootstrap.php';
    if (file_exists($file)) {
        require $file;
        break;
    }
}

if ($_SERVER['APP_DEBUG']) {
    umask(0000);

    if (class_exists(Debug::class)) {
        Debug::enable();
    }
}

$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG'], $_SERVER['DATABASE_URL']);
$application = new Application($kernel);
$application->run($input);
