<?php

use SilverStripe\Control\HTTPApplication;
use SilverStripe\Control\HTTPRequestBuilder;
use SilverStripe\Core\CoreKernel;
use SilverStripe\Core\Environment;

// Find autoload.php
if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
    require __DIR__ . '/../vendor/autoload.php';
} elseif (file_exists(__DIR__ . '/vendor/autoload.php')) {
    require __DIR__ . '/vendor/autoload.php';
} else {
    header('HTTP/1.1 500 Internal Server Error');
    echo "autoload.php not found";
    exit(1);
}

if (Environment::getEnv("SS_DATABASE_USERNAME") === false)
{
    Environment::setEnv("SS_DATABASE_USERNAME", Environment::getEnv("MYSQL_USERNAME") ?: "root");
}

if (Environment::getEnv("SS_DATABASE_PASSWORD") === false)
{
    Environment::setEnv("SS_DATABASE_PASSWORD", Environment::getEnv("MYSQL_PASSWORD") ?: Environment::getEnv("MYSQL_ROOT_PASSWORD"));
}

if (Environment::getEnv("SS_DATABASE_NAME") === false)
{
    Environment::setEnv("SS_DATABASE_NAME", Environment::getEnv("MYSQL_DATABASE"));
}

// Build request and detect flush
$request = HTTPRequestBuilder::createFromEnvironment();

// Default application
$kernel = new CoreKernel(BASE_PATH);
$app = new HTTPApplication($kernel);
$response = $app->handle($request);
$response->output();