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

use Symfony\Component\Console\Input\ArgvInput;
use DRI\SugarCRM\Console\Console\Application as SugarConsole;
use DRI\SugarCRM\Console\Application as SugarApp;

set_time_limit(0);

try {
    $base_path = realpath(__DIR__ . '/../../../..');
    $include_path = "$base_path/docroot";
    $autoload_path = "$base_path/vendor";
    $console_path = dirname(__DIR__);

    $cwd = getcwd();

    // Check if the console is located inside a SugarCRM project
    if (!file_exists("$include_path/sugar_version.php")
        || !file_exists("$autoload_path/autoload.php")) {
        // We are not, try to find the current base path..
        $include_path = $cwd . '/';

        while (!file_exists($include_path . 'sugar_version.php') && $include_path != '//')
        {
            if (file_exists($include_path . 'docroot/sugar_version.php'))
            {
                $include_path .= 'docroot/';
            }
            else
            {
                $include_path = dirname($include_path) . '/';
            }
        }

        if ($include_path == '//')
        {
            throw new Exception("Could not find sugarcrm base path in: $cwd");
        }

        $include_path = rtrim($include_path, '/');
        $autoload_path = dirname(__DIR__) . "/vendor";

        if (!file_exists("$autoload_path/autoload.php")) {
            throw new Exception("vendor/autoload.php isn't generated");
        }
    }

    // Change directory to the current SugarCRM application that we work on
    set_include_path($include_path);
    chdir($include_path);
    define('sugarEntry', true);

    // Initalize autoloading features
    require_once "$autoload_path/autoload.php";

    // Initalize and execute command
    $input = new ArgvInput($argv);

    $sugar = new SugarApp(
        $include_path,
        $console_path
    );

    $console = new SugarConsole($sugar);

    $console->run($input);
} catch (\Exception $e) {
    if (in_array('--verbose', $argv) || in_array('-v', $argv) || in_array('-vv', $argv) || in_array('-vvv', $argv)) {
        throw $e;
    } else {
        echo "{$e->getMessage()}\n";
    }
}
