#!/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';

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

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

$databaseUrl = (string) EnvironmentHelper::getVariable('DATABASE_URL', getenv('DATABASE_URL'));
if (trim($databaseUrl ?? '') === '') {
    // fake DATABASE_URL
    $_SERVER['DATABASE_URL'] = Kernel::PLACEHOLDER_DATABASE_URL;

    if (\class_exists(ComposerPluginLoader::class) && method_exists(InstalledVersions::class, 'getInstalledPackagesByType')) {
        $pluginLoader = new ComposerPluginLoader($classLoader, null);
    }
} elseif (!EnvironmentHelper::hasVariable('INSTALL')) {
    $pluginLoader = new DbalKernelPluginLoader($classLoader, null, \Shopware\Core\Kernel::getConnection());
}

if ($debug) {
    umask(0000);
    if (class_exists(Debug::class)) {
        Debug::enable();
    }
}

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