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

if (version_compare('7.1.0', PHP_VERSION, '>')) {
    fwrite(
        STDERR,
        sprintf(
            'This version of piecrust is supported on PHP 7.1.' . PHP_EOL .
            'You are using PHP %s (%s).' . PHP_EOL,
            PHP_VERSION,
            PHP_BINARY
        )
    );

    die(1);
}

if (!ini_get('date.timezone')) {
    ini_set('date.timezone', 'UTC');
}


if (php_sapi_name() == "cli") {
    $libsDir = null;
    if (is_dir('./vendor')) {
        $libsDir = './vendor';
    }
    if( strpos($_SERVER['PHP_SELF'], '/vendor/' )!== false ) {
        $libsDir = substr($_SERVER['PHP_SELF'], 0, strpos($_SERVER['PHP_SELF'], '/vendor/' )).'/vendor';
    }

    if ($libsDir) {
        require_once $libsDir . '/autoload.php';
    }
    unset($libsDir);
}

foreach (array(__DIR__ . '/../../autoload.php', __DIR__ . '/../vendor/autoload.php', __DIR__ . '/vendor/autoload.php') as $file) {
    if (file_exists($file)) {
        define('PHPUNIT_COMPOSER_INSTALL', $file);

        break;
    }
}

unset($file);

if (!defined('PHPUNIT_COMPOSER_INSTALL')) {
    fwrite(STDERR,
        'You need to set up the project dependencies using the following commands:' . PHP_EOL .
        'wget http://getcomposer.org/composer.phar' . PHP_EOL .
        'php composer.phar install' . PHP_EOL
    );

    die(1);
}

require_once PHPUNIT_COMPOSER_INSTALL;

error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE & ~E_STRICT);

try {
   $returnCode = piecrust_command();
} catch ( Exception $e ) {
    //fwrite(STDERR, $e->getMessage() . PHP_EOL . $e->getTraceAsString());
    throw $e;
    die(2);
}
exit($returnCode);

/**
 * Shows a hard-coded system message.
 */
function piecrust_show_system_message($message, $details = null)
{
    $contents = file_get_contents(__DIR__ . '/res/messages/' . $message . '.html');
    if ($details != null)
    {
        $contents = str_replace('{{ details }}', $details, $contents);
    }
    echo $contents;
}

/**
 * The PieCrust error handler.
 */
function piecrust_error_handler($errno, $errstr, $errfile = null, $errline = 0, $errcontext = null)
{
    if (error_reporting() & $errno) {
       // throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
    }
    return;
}

/**
 * The PieCrust shutdown function.
 */
function piecrust_shutdown_function()
{
    $error = error_get_last();
    if ($error)
    {
        try
        {
            $guard = 100;
            while (ob_get_level() > 0 && (--$guard) > 0)
                ob_end_clean();
        }
        catch (Exception $e)
        {
        }

        piecrust_show_system_message('critical', "{$error['message']} in '{$error['file']}:{$error['line']}'");
        exit();
    }
}

/**
 * The Chef shutdown function (command-line version of `piecrust_shutdown_function`).
 */
function chef_shutdown_function()
{
    $error = error_get_last();
    if ($error)
    {
        try
        {
            $guard = 100;
            while (ob_get_level() > 0 && (--$guard) > 0)
                ob_end_clean();
        }
        catch (Exception $e)
        {
        }

        echo "Critical error in '{$error['file']}:{$error['line']}': {$error['message']}\n";
        exit();
    }
}

/**
 * Sets up basic things like the global error handler or the timezone.
 */
function piecrust_setup($profile = 'web')
{
    // Set error handling.
    switch ($profile)
    {
    case 'web':
        {
            set_error_handler('piecrust_error_handler');
            register_shutdown_function('piecrust_shutdown_function');
            break;
        }
    case 'piecrust':
    default:
        {
            ini_set('display_errors', true);
            ini_set("memory_limit", "-1");
            error_reporting(E_ALL);
            set_error_handler('piecrust_error_handler');
            register_shutdown_function('chef_shutdown_function');
            break;
        }
    case 'test':
        {
            ini_set('display_errors', true);
            ini_set('display_startup_errors', true);
            error_reporting(E_ALL | E_STRICT);
            set_error_handler('piecrust_error_handler');
            break;
        }
    }
}


/**
 * Setups and runs a new PieCrust app with the given parameters, requesting the given URI.
 */
function piecrust_run($parameters = array(), $uri = null, $profile = 'web')
{
    piecrust_setup($profile);

    $parameters = PieCrust\Runner\PieCrustRunner::getPieCrustParameters($parameters);
    $pieCrust = new PieCrust\PieCrust($parameters);
    $runner = new PieCrust\Runner\PieCrustRunner($pieCrust);
    $runner->run($uri);
}

/**
 * Setups and runs a new instance of Chef.
 */
function piecrust_command($userArgv = null, $profile = 'piecrust')
{
    piecrust_setup($profile);

    $chef = new PieCrust\Command\Command();
    //$chef->setup();
    return $chef->run($userArgv);
}
