<?php
/**
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 * @link          https://cakephp.org CakePHP(tm) Project
 * @since         3.0.0
 * @license       MIT License (https://opensource.org/licenses/mit-license.php)
 */

if (!defined('DS')) {
    define('DS', DIRECTORY_SEPARATOR);
}

define('ROOT', dirname(__DIR__));
define('APP_DIR', 'src');
define('APP', ROOT . DS . APP_DIR . DS);
define('CONFIG', ROOT . DS . 'config' . DS);
define('WWW_ROOT', ROOT . DS . 'webroot' . DS);
define('TESTS', ROOT . DS . 'tests' . DS);

$ensureDirectory = static function (string $path): bool {
    if (!is_dir($path)) {
        @mkdir($path, 0775, true);
    }

    return is_dir($path) && is_writable($path);
};

$projectRuntimeRoot = ROOT . DS;
$preferredRuntimeRoot = getenv('APP_RUNTIME_DIR');
if (is_string($preferredRuntimeRoot) && $preferredRuntimeRoot !== '') {
    $projectRuntimeRoot = rtrim($preferredRuntimeRoot, DS) . DS;
}

$tmpPath = $projectRuntimeRoot === ROOT . DS ? ROOT . DS . 'tmp' . DS : $projectRuntimeRoot . 'tmp' . DS;
$logsPath = $projectRuntimeRoot === ROOT . DS ? ROOT . DS . 'logs' . DS : $projectRuntimeRoot . 'logs' . DS;

if (!$ensureDirectory($tmpPath) || !$ensureDirectory($logsPath)) {
    $fallbackRuntimeRoot = rtrim(sys_get_temp_dir(), DS) . DS . basename(ROOT) . DS . 'runtime' . DS;
    $tmpPath = $fallbackRuntimeRoot . 'tmp' . DS;
    $logsPath = $fallbackRuntimeRoot . 'logs' . DS;

    $ensureDirectory($tmpPath);
    $ensureDirectory($logsPath);
}

foreach ([
    $tmpPath . 'cache' . DS,
    $tmpPath . 'cache' . 'models' . DS,
    $tmpPath . 'cache' . 'persistent' . DS,
    $tmpPath . 'cache' . 'views' . DS,
    $tmpPath . 'sessions' . DS,
    $tmpPath . 'tests' . DS,
] as $runtimePath) {
    $ensureDirectory($runtimePath);
}

define('TMP', $tmpPath);
define('LOGS', $logsPath);
define('CACHE', TMP . 'cache' . DS);
define('RESOURCES', ROOT . DS . 'resources' . DS);
define('CAKE_CORE_INCLUDE_PATH', ROOT . DS . 'vendor' . DS . 'cakephp' . DS . 'cakephp');
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
define('CAKE', CORE_PATH . 'src' . DS);
