<?php

declare(strict_types=1);

/*
 * This file is part of Contao.
 *
 * (c) Leo Feyer
 *
 * @license LGPL-3.0-or-later
 */

use Composer\Autoload\ClassLoader;
use Contao\CoreBundle\Response\InitializeControllerResponse;
use Contao\ManagerBundle\HttpKernel\ContaoKernel;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\HttpFoundation\Request;

if (!defined('TL_SCRIPT')) {
    die('Your script is not compatible with Contao 4.');
}

// Disable the phar stream wrapper for security reasons (see #105)
if (in_array('phar', stream_get_wrappers(), true)) {
    stream_wrapper_unregister('phar');
}

/** @var ClassLoader $loader */
$loader = require __DIR__.'/../vendor/autoload.php';

if ('cli' === PHP_SAPI || !isset($_SERVER['REQUEST_URI'])) {
    $kernel = ContaoKernel::fromInput(dirname(__DIR__), new ArgvInput());
    $kernel->boot();
    $kernel->getContainer()->get('contao.framework')->initialize();
} else {
    $request = Request::create('/_contao/initialize', 'GET', [], $_COOKIE, [], $_SERVER);
    $request->attributes->set('_scope', 'BE' === TL_MODE ? 'backend' : 'frontend');

    $kernel = ContaoKernel::fromRequest(dirname(__DIR__), $request);
    $response = $kernel->handle($request);

    // Send the response if not generated by the InitializeController
    if (!$response instanceof InitializeControllerResponse) {
        $response->send();
        $kernel->terminate($request, $response);
        exit;
    }
}
