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

use Shopware\Core\DevOps\Environment\EnvironmentHelper;
use Shopware\Core\Framework\Plugin\KernelPluginLoader\ComposerPluginLoader;
use Shopware\Core\HttpKernel;
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 HEPTAconnect 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()->bootEnv($projectRoot . '/.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();
    }
}

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

$databaseUrl = (string) EnvironmentHelper::getVariable('DATABASE_URL', \getenv('DATABASE_URL'));

if (\trim($databaseUrl ?? '') === '') {
    $_SERVER['SHOPWARE_SKIP_CONNECTION_VARIABLES'] = true;
}

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

$application = new Application($kernel->getKernel());
$application->run($input);
