#!/usr/bin/env php
<?php

function writeErrorAndExit(string $error)
{
    fwrite(STDERR, $error);
    exit(1);
}

function findFileByTraversingUp(string $dir, string $filePath)
{
    $absoluteFilePath = $dir.DIRECTORY_SEPARATOR.$filePath;
    if (file_exists($absoluteFilePath)) {
        return $dir;
    } else {
        $parentDir = dirname($dir);
        if ($parentDir === $dir) {
            return false;
        }

        return findFileByTraversingUp($parentDir, $filePath);
    }
}

$absolutePath = realpath(__DIR__);
$autoloadRelativePath = 'vendor'.DIRECTORY_SEPARATOR.'autoload.php';

$projectRootDir = findFileByTraversingUp(dirname(dirname($absolutePath)), $autoloadRelativePath);
if (false === $projectRootDir) {
    $autoloadRelativePath = 'vendor'.DIRECTORY_SEPARATOR.'autoload.php';
    $projectRootDir = findFileByTraversingUp($absolutePath, $autoloadRelativePath);
}
if (false === $projectRootDir) {
    writeErrorAndExit('There was no autoload.php file found, hence the dependencies could not be loaded.');
} else {
    chdir($projectRootDir);
    require $autoloadRelativePath;
}

use Agnes\AgnesFactory;
use Symfony\Component\Console\Application;
use Symfony\Component\Dotenv\Dotenv;

if (file_exists('.env')) {
    $dotenv = new Dotenv(false);
    $dotenv->loadEnv('.env');
}

$app = new Application();

$app->addCommands(AgnesFactory::getCommands());

$app->run();
