#!/usr/bin/env php
<?php
// Bootstrap Arvici.
defined('DS') || define('DS', DIRECTORY_SEPARATOR);

// Detect root and vendor paths.
$detectLocations = [
    realpath(getcwd()),
    dirname(__DIR__),
    __DIR__,
];
$composerDir = null;
$baseDir = null;
$appDir = null;

foreach ($detectLocations as $location) {
    if ($composerDir === null && file_exists($location . DS . 'composer.json')) {
        if (! file_exists($location . DS . 'vendor' . DS . 'autoload.php')) {
            echo $location;
            echo "Run composer install/update first!";
            exit();
        }
        $composerDir = $location;
    }
    if ($baseDir === null && (is_dir($location . DS . 'public') || is_file(dirname($location) . DS . 'bootstrap.php'))) {
        $baseDir = $location;
    }
}

if (! $composerDir) {
    echo 'Composer not found!';
    exit();
} elseif (! $baseDir) {
    echo 'Base directory not found!';
    exit();
}

// Determinate app dir.
if (is_dir($baseDir . DS . 'App')) {
    $appDir = $baseDir . DS . 'App';
} elseif (is_dir($appDir = $baseDir . DS . 'app' . DS . 'App')) {
    $appDir = $baseDir . DS . 'app' . DS . 'App';
}
if (! $appDir) {
    echo 'Main App directory not found!';
    exit();
}

// Define locations.
defined('BASEPATH') || define('BASEPATH', $baseDir . DS);
defined('APPPATH') || define('APPPATH', $appDir . DS);

// Require composer autoload!
require_once $composerDir . DS . 'vendor' . DS .'autoload.php';

unset($baseDir);
unset($detectLocations);

// Load configuration
$configDir = APPPATH . '/Config/';
foreach (glob($configDir . '*.php') as $fileName) {
    require_once $fileName;
}
unset($configDir);

// Call the application bootstrap.
use Arvici\Heart\Console\Application;

$application = new Application();
$application->prepare();
$application->run();
