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

// if you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);

set_time_limit(0);

require_once __DIR__ . '/bootstrap.php';
require_kernel();

use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Debug\Debug;

$input = new ArgvInput();
$env = $input->getParameterOption(array('--env', '-e'), getenv('SYMFONY_ENV') ?: 'dev');
$debug = getenv('SYMFONY_DEBUG') !== '0' && !$input->hasParameterOption(array('--no-debug', '')) && $env !== 'prod';

if ($debug) {
    Debug::enable();
}

$kernel = new AppKernel($env, $debug);
$application = new Application($kernel);
$application->run($input);

// register all commands available by our bundles
$adminPool = $kernel->getContainer()->get('sulu_admin.admin_pool');
foreach ($adminPool->getCommands() as $command) {
    $application->add($command);
}

function require_kernel()
{
    $dirs = [ 'app', 'tests', 'Tests/app' ];

    if ($kernelDir = getenv('KERNEL_DIR')) {
        array_unshift($dirs, $kernelDir);
    }

    if (!$kernelDir) {
        require_once(__DIR__ . '/../../Tests/app/AppKernel.php');

        return;
    }

    $found = false;

    foreach ($dirs as $dir) {
        // TODO: Use autoloading for the kernel.
        $kernelPath = sprintf('%s/AppKernel.php', $dir);

        if (file_exists($kernelPath)) {
            $found = true;
            break;
        }
    }

    if (false === $found) {
        echo sprintf('Could not find kernel looked in: "%s"', implode('", "', $dirs));
        exit(1);
    }

    require_once $kernelPath;
}
