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

/**
 * bin/console
 *
 * @package   OpenEMR
 * @link      https://www.open-emr.org
 * @author    Brady Miller <Brady Miller <brady.g.miller@gmail.com>
 * @copyright Copyright (c) 2022 Brady Miller <Brady Miller <brady.g.miller@gmail.com>
 * @license   https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
 */

if (php_sapi_name() !== 'cli') {
    echo "Only php cli can execute a command\n";
    die();
}

$fileRoot = dirname(__DIR__);
require_once "{$fileRoot}/vendor/autoload.php";

$skipGlobals = in_array('--skip-globals', $argv, true);
// Don't pass --skip-globals to Symfony, and reindex array
$argv = array_values(array_diff($argv, ['--skip-globals']));

// Extract site if provided
$siteArgs = preg_grep('/^--site=(.*)$/', $argv);
$siteDefault = $siteArgs ? end(explode('=', reset($siteArgs))) : 'default';
$_SERVER['argv'] = $argv;

$commandRunner = new \OpenEMR\Common\Command\SymfonyCommandRunner();
if ($skipGlobals) {
    // Minimal bootstrap without database
    $GLOBALS['fileroot'] = $fileRoot;

    // Set up a minimal event dispatcher for commands that don't need database
    $oeGlobals = new \OpenEMR\Core\OEGlobalsBag();

    $eventDispatcher = new \Symfony\Component\EventDispatcher\EventDispatcher();
    $commandRunner->setEventDispatcher($eventDispatcher);
} else {
    $_GET['site'] = $siteDefault;

    $ignoreAuth = true;
    // Since from command line, set $sessionAllowWrite since need to set site_id session and no benefit to set to false
    $sessionAllowWrite = true;
    $oeGlobals = require_once "{$fileRoot}/interface/globals.php";
}
$commandRunner->setGlobalsBag($oeGlobals);
$commandRunner->run();
