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

if (PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg') {
    echo 'Warning: Humbug may only be invoked from a command line', PHP_EOL;
}

require_once __DIR__ . '/../bootstrap.php';

use Humbug\Console\Application;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\Output\ConsoleOutput;

if (function_exists('date_default_timezone_set')
&& function_exists('date_default_timezone_get')) {
    date_default_timezone_set(@date_default_timezone_get());
}

error_reporting(-1);
if (function_exists('ini_set')) {
    @ini_set('display_errors', 1);
}

$dispatcher = new \Symfony\Component\EventDispatcher\EventDispatcher();
$dispatcher->addListener(ConsoleEvents::COMMAND, function(ConsoleCommandEvent $event){
    $application = $event->getCommand()->getApplication();
    $event->getOutput()->writeln($application->getLongVersion() . PHP_EOL);
});

$output = new ConsoleOutput();

$input = new \Symfony\Component\Console\Input\ArgvInput(prepareArgv());

$application = new Application();
if ('phar:' !== substr(__FILE__, 0, 5)) {
    $application->setDispatcher($dispatcher);
} else {
    $output->writeln($application->getLongVersion() . PHP_EOL);
}

$application->add(new \Humbug\Command\Humbug());
$application->add(new \Humbug\Command\Configure());
$application->add(new \Humbug\Command\Stats());


if ('phar:' === substr(__FILE__, 0, 5)) {
    $application->add(new \Humbug\Command\SelfUpdate());
}

function prepareArgv()
{
    $argv = $_SERVER['argv'];

    $found = false;

    while (next($argv)) {
        $value = current($argv);
        if (!$value || '-' !== $value[0]) {
            $found = true;
        }
    }

    if (!$found) {
        $argv[] = 'run';
    }

    return $argv;
}

$application->run($input, $output);
