#!/usr/bin/env php
<?php
/*
 * Your installation or use of this SugarCRM file is subject to the applicable
 * terms available at
 * http://support.sugarcrm.com/Resources/Master_Subscription_Agreements/.
 * If you do not agree to all of the applicable terms or do not have the
 * authority to bind the entity as an authorized representative, then do not
 * install or use this SugarCRM file.
 *
 * Copyright (C) SugarCRM Inc. All rights reserved.
 */

use Sugarcrm\Sugarcrm\AccessControl\AdminWork;
use Sugarcrm\Sugarcrm\Console\Application;
use Sugarcrm\Sugarcrm\Console\CommandRegistry\CommandRegistry;
use Sugarcrm\Sugarcrm\DependencyInjection\Container;
use Sugarcrm\Sugarcrm\Security\Context;
use Sugarcrm\Sugarcrm\Security\Subject\Cli;

if (PHP_SAPI !== 'cli') {
    die('This command can only be invoked from the command line.' . PHP_EOL);
}

if (!file_exists(__DIR__ . '/../vendor/autoload.php')) {
    die('Run "composer install" before using SugarCRM Console' . PHP_EOL);
}

/**
 * Below code was part of `Sugarcrm\Sugarcrm\Console\Bootstrap::run()`. However
 * because of entryPoint requiring direct access to globals this has been moved
 * temporary to this spot until entryPoint gets its facts straight.
 */
 
define('sugarEntry', true);

// use sugar root as base directory
$sugarBaseDir = str_replace('\\', '/', realpath(__DIR__ . '/..'));
chdir($sugarBaseDir);

// try to load config as we ship an empty one
if (file_exists('config.php')) {
    include 'config.php';
}

if (file_exists('config_override.php')) {
    include 'config_override.php';
}

// determine if sugar has been installed or not
if (!empty($sugar_config['dbconfig']['db_name'])) {
    define('ENTRY_POINT_TYPE', 'api');
    require_once 'include/entryPoint.php';
    $GLOBALS['current_user']->getSystemUser();

    // allow admin to access everything
    $adminWork = new AdminWork();
    $adminWork->startAdminWork();

    $context = Container::getInstance()->get(Context::class);
    $subject = new Cli();
    $context->activateSubject($subject);

    $mode = CommandRegistry::MODE_INSTANCE;
} else {
    require 'vendor/autoload.php';
    $mode = CommandRegistry::MODE_STANDALONE;
}

// load custom commands from extension framework regardless of mode
if ($extension = SugarAutoLoader::loadExtension('console')) {
    require $extension;
}

$application = Application::create($mode);
$application->setAutoExit(false);
$exitCode = $application->run();

if (isset($context, $subject)) {
    $context->deactivateSubject($subject);
}
