<?php
/* SVN FILE: $Id$ */
/**
 * This file transfers control over to the dispatcher which will invoke the
 * appropriate controller. We also handle any exceptions that were not handled
 * elsewhere in the application, so we can end gracefully.
 *
 * @package       minPHP
 * @version       $Revision$
 * @modifiedby    $LastChangedBy$
 * @lastmodified  $Date$
 */

$start = microtime(true);

try {
    include(dirname(__FILE__) . '/lib/init.php');

    // The SAPI determines CLI mode — never the absence of REQUEST_URI alone.
    // CGI/FCGI/LSAPI handlers export request metadata such as REQUEST_URI as
    // real environment variables, which child processes inherit and the CLI
    // SAPI surfaces in $_SERVER; keying on REQUEST_URI would make a CLI
    // invocation spawned from a web request dispatch as a web request.
    // An empty REQUEST_URI still falls back to CLI dispatch so cron jobs
    // running under a CGI binary continue to work.
    if (PHP_SAPI === 'cli' || empty($_SERVER['REQUEST_URI'])) {
        // Dispatch the CLI request
        Dispatcher::dispatchCli($argv);
    } else {
        // Dispatch the Web request
        Dispatcher::dispatch($_SERVER['REQUEST_URI']);
    }
} catch (Throwable $e) {
    // Attempt to log the error
    try {
        if (($container = Configure::get('container'))) {
            $logger = $container->get('logger');
            $logger->error($e);
        }
    } catch (Throwable $ex) {
        // Nothing to do
    }

    // In CLI, report the failure and exit non-zero so callers (cron wrappers,
    // the upgrade orchestrator) can detect it. Dispatcher::raiseError() prints
    // nothing when error_reporting is 0, which would otherwise turn a fatal
    // error into a silent exit code 0.
    if (PHP_SAPI === 'cli') {
        fwrite(STDERR, get_class($e) . ': ' . $e->getMessage() . "\n");
        exit(1);
    }

    try {
        // Clear all existing buffer output safely
        while (ob_get_level() > 0) {
            ob_end_clean();
        }

        // Attempt to raise any error, gracefully
        Dispatcher::raiseError($e);
    } catch (Throwable $e) {
        if (Configure::get('System.debug')) {
            echo $e->getMessage() . ' on line <strong>' . $e->getLine() .
                '</strong> in <strong>' . $e->getFile() . "</strong>\n" .
                '<br />Printing Stack Trace:<br />' . nl2br($e->getTraceAsString());
        } else {
            echo $e->getMessage();
        }
    }
}

$end = microtime(true);

// Display rendering time if benchmarking is enabled
if (Configure::get('System.benchmark')) {
    echo 'execution time: ' . ($end - $start) . ' seconds';
}
