#!/usr/bin/env php
<?php
/**
 * Shared CLI bootstrap for exploitation scripts.
 *
 * Provides:
 *   - ROOT_PATH, LIB_PATH, WEBROOT_PATH … (via lib/Config.php)
 *   - Class autoloader (lib/*.php)
 *   - Singletons: $db (Database), $settings (Settings), $logger (Logger)
 *   - $moduleRegistry (Module) with all module descriptors loaded
 *   - $i18n (I18n) initialized with the app default language
 *   - CLI session stub (prevents errors when web code is called from CLI)
 *   - cli_show_help() helper to extract --help text from docblocks
 *
 * Usage from exploitation/<subdir>/script.php:
 *   require_once dirname(__DIR__) . '/shared/cli_bootstrap.php';
 *
 * Usage from exploitation/script.php (shim):
 *   require_once __DIR__ . '/shared/cli_bootstrap.php';
 */

// Sécurité : les scripts d'exploitation vivent désormais sous mon-appli/
// (DocumentRoot Apache) et ne doivent JAMAIS s'exécuter via le serveur web.
// Tout SAPI non-CLI est refusé avant le moindre traitement.
if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    header('Content-Type: text/plain; charset=UTF-8');
    echo "Forbidden: command-line execution only.\n";
    exit(1);
}

if (!defined('ROOT_PATH')) {
    define('ROOT_PATH', dirname(__DIR__, 2));
}

require_once ROOT_PATH . '/lib/Config.php';

if (!is_dir(LOG_PATH)) mkdir(LOG_PATH, 0750, true);

spl_autoload_register(function (string $class): void {
    $file = LIB_PATH . '/' . $class . '.php';
    if (file_exists($file)) require_once $file;
});

if (php_sapi_name() === 'cli') {
    Session::start();
}

$db       = Database::getInstance();
$settings = Settings::getInstance();
$logger   = Logger::getInstance();

$moduleRegistry = Module::getInstance();
foreach (glob(WEBROOT_PATH . '/modules/*/module.php') ?: [] as $_mf) {
    $_desc = require $_mf;
    if (is_array($_desc)) $moduleRegistry->register($_desc);
}
unset($_mf, $_desc);

$moduleRegistry->migrateConfigsFromDb();

$i18n = I18n::getInstance();
$i18n->init($settings->get('default_language', DEFAULT_LANGUAGE));

/**
 * Extract and display help text from the calling script's docblock,
 * then exit. Pass __FILE__ from the script.
 */
function cli_show_help(string $scriptFile): never
{
    $lines = file($scriptFile);
    foreach ($lines as $line) {
        if (str_starts_with($line, ' *')) echo substr($line, 3);
        if ($line === " */\n") break;
    }
    exit(0);
}
