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

if (strpos($argv[0], 'console') !== false && strpos(implode('', $argv), 'pgs') !== false) {
  echo "You cannot run PGS command with {$argv[0]}\n";
  exit(255);
}

use App\Application;
use App\Kernel;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Debug\Debug;

if (false === in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true)) {
    echo 'Warning: The console should be invoked via the CLI version of PHP, not the '.\PHP_SAPI.' SAPI'.\PHP_EOL;
}

set_time_limit(0);

require dirname(__DIR__).'/vendor/autoload.php';

$input = new ArgvInput();

if ($input->hasParameterOption('--no-debug', true)) {
    putenv('PGS_DEBUG='.$_SERVER['PGS_DEBUG'] = $_ENV['PGS_DEBUG'] = '0');
}
if (null !== $logfile = $input->getParameterOption(['--logfile'], null, true)) {
    putenv('PGS_LOG_FILE='.$_SERVER['PGS_LOG_FILE'] = $_ENV['PGS_LOG_FILE'] = $logfile);
}
if (null !== $loglevel = $input->getParameterOption(['--loglevel'], null, true)) {
    putenv('PGS_LOG_LEVEL='.$_SERVER['PGS_LOG_LEVEL'] = $_ENV['PGS_LOG_LEVEL'] = $loglevel);
}

require dirname(__DIR__).'/config/bootstrap.php';

if ($_SERVER['PGS_DEBUG']) {
    umask(0000);

    if (class_exists(Debug::class)) {
        Debug::enable();
    }
}

$kernel = new Kernel('cli', (bool) $_SERVER['PGS_DEBUG']);
$application = new Application($kernel);
$application->run($input);
