#!/usr/bin/env php
<?php declare(strict_types=1);

use Composer\InstalledVersions;
use Shopware\Core\DevOps\Environment\EnvironmentHelper;
use Shopware\Core\Framework\Plugin\KernelPluginLoader\ComposerPluginLoader;
use Shopware\Core\Framework\Plugin\KernelPluginLoader\DbalKernelPluginLoader;
use Shopware\Core\Framework\Plugin\KernelPluginLoader\StaticKernelPluginLoader;
use Shopware\Production\HttpKernel;
use Shopware\Production\Kernel;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Dotenv\Dotenv;
use Symfony\Component\ErrorHandler\Debug;

if (\PHP_VERSION_ID < 70403) {
    echo 'Your cli is running PHP version ' . \PHP_VERSION . ' but Shopware 6 requires at least PHP 7.4.3' . \PHP_EOL;
    exit(1);
}

set_time_limit(0);

$classLoader = require __DIR__ . '/../vendor/autoload.php';

if (!class_exists(Application::class)) {
    throw new RuntimeException('You need to add "symfony/framework-bundle" as a Composer dependency.');
}

$projectRoot = dirname(__DIR__);
if (class_exists(Dotenv::class) && (file_exists($projectRoot . '/.env.local.php') || file_exists($projectRoot . '/.env') || file_exists($projectRoot . '/.env.dist'))) {
    (new Dotenv())->usePutenv()->setProdEnvs(['prod', 'e2e'])->bootEnv(dirname(__DIR__) . '/.env');
}

if (!EnvironmentHelper::hasVariable('PROJECT_ROOT')) {
    $_SERVER['PROJECT_ROOT'] = $projectRoot;
}

$input = new ArgvInput();
$env = $input->getParameterOption(['--env', '-e'], $_SERVER['APP_ENV'] ?? 'prod', true);
$debug = ($_SERVER['APP_DEBUG'] ?? ($env !== 'prod')) && !$input->hasParameterOption('--no-debug', true);

if ($debug) {
    umask(0000);

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

$pluginLoader = new StaticKernelPluginLoader($classLoader, null);

$shopwareVersion = InstalledVersions::getVersion('shopware/core') . '@' . InstalledVersions::getReference('shopware/core');

if ($input->getFirstArgument() === 'system:install') {
    $_SERVER['INSTALL'] = true;
}

$databaseUrl = (string) EnvironmentHelper::getVariable('DATABASE_URL', getenv('DATABASE_URL'));
if (trim($databaseUrl ?? '') === '') {
    // fake DATABASE_URL
    $_SERVER['DATABASE_URL'] = Kernel::PLACEHOLDER_DATABASE_URL;
} elseif (!EnvironmentHelper::hasVariable('INSTALL')) {
    $pluginLoader = new DbalKernelPluginLoader($classLoader, null, \Shopware\Core\Kernel::getConnection());
}

if ($_SERVER['COMPOSER_PLUGIN_LOADER'] ?? $_SERVER['DISABLE_EXTENSIONS'] ?? false) {
    $pluginLoader = new ComposerPluginLoader($classLoader);
}

$kernel = new HttpKernel($env, $debug, $classLoader);
$kernel->setPluginLoader($pluginLoader);

$application = new Application($kernel->getKernel());
$kernel->getKernel()->boot();
$application->setName('Shopware');
$application->setVersion($kernel->getKernel()->getContainer()->getParameter('kernel.shopware_version'));
$application->run($input);
