#!/usr/bin/env php
<?php
/**
 * Pimcore
 *
 * This source file is available under two different licenses:
 * - GNU General Public License version 3 (GPLv3)
 * - Pimcore Enterprise License (PEL)
 * Full copyright and license information is available in
 * LICENSE.md which is distributed with this source code.
 *
 * @copyright  Copyright (c) Pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     GPLv3 and PEL
 */

use Pimcore\Config;
use Pimcore\Install\InstallerKernel;
use Pimcore\Version;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Debug\Debug;

error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
@ini_set('display_errors', 'On');

$maxExecutionTime = 0;
@ini_set('max_execution_time', $maxExecutionTime);
set_time_limit($maxExecutionTime);

if (!defined('PIMCORE_PROJECT_ROOT')) {
    define(
        'PIMCORE_PROJECT_ROOT',
        getenv('PIMCORE_PROJECT_ROOT')
            ?: getenv('REDIRECT_PIMCORE_PROJECT_ROOT')
            ?: realpath(__DIR__ . '/..')
    );
}

/** @var $loader \Composer\Autoload\ClassLoader */
$loader = include PIMCORE_PROJECT_ROOT . '/vendor/autoload.php';
Pimcore::setAutoloader($loader);

require_once PIMCORE_PROJECT_ROOT . '/pimcore/config/constants.php';
require_once PIMCORE_PROJECT_ROOT . '/pimcore/lib/helper-functions.php';

Debug::enable();

if (!class_exists('Zend_Date')) {
    // if ZF is not loaded, we need to provide some compatibility stubs
    // for a detailed description see the included file
    require_once PIMCORE_PATH . '/stubs/compatibility-v4.php';
}

$kernel = new InstallerKernel(PIMCORE_PROJECT_ROOT, Config::getEnvironment(), true);
Pimcore::setKernel($kernel);

$application = new Application($kernel);
$application->setName('Pimcore Installer');
$application->setVersion(Version::getVersion());
$application->setDefaultCommand('pimcore:install');

// In previous versions, this was to be called with bin/install and defined pimcore:install as single command (second parameter
// to setDefaultCommand. As we now have multiple commands, we need to remove the single command flag, but that removes
// the ability to call bin/console without the pimcore:install argument but with arguments as that is not supported by
// Symfony. This block fetches the first argument from the input object and injects "pimcore:install" if there is no first
// argument or the first argument is no valid command.
$input         = new ArgvInput();
$firstArgument = $input->getFirstArgument();

// set pimcore:install as first argument to enable default command with arguments
if (null === $firstArgument || !$application->has($firstArgument)) {
    $argv = $_SERVER['argv'];

    $applicationName = array_shift($argv);
    array_unshift($argv, 'pimcore:install');
    array_unshift($argv, $applicationName);

    $input = new ArgvInput($argv);
}

// run application with the input resolved before
$application->run($input);
