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



declare(strict_types=1);

if (php_sapi_name() !== 'cli') {
    echo "This installer runs on the command line only.\n";
    exit(2);
}

 

$argvList = $argv ?? [];
array_shift($argvList);  

$flags = [];    
foreach ($argvList as $arg) {
    if ($arg === '--help' || $arg === '-h') { $flags['help'] = true; continue; }
    if (preg_match('/^--([a-z][a-z0-9-]*)(?:=(.*))?$/s', $arg, $m)) {
        $flags[$m[1]] = $m[2] ?? true;
    } else {
        fwrite(STDERR, "Unrecognised argument: {$arg}\n");
        exit(2);
    }
}

$asJson = !empty($flags['json']);

if (!empty($flags['help'])) {
     
    $self = file_get_contents(__FILE__);
    if ($self !== false && preg_match('#/\*\*(.*?)\*/#s', $self, $mm)) {
        echo preg_replace('/^ ?\* ?/m', '', trim($mm[1])) . "\n";
    }
    exit(0);
}

 
$fileCfg = [];
if (!empty($flags['config']) && is_string($flags['config'])) {
    $raw = @file_get_contents($flags['config']);
    if ($raw === false) {
        fail_out($asJson, 'usage', "Could not read --config file: {$flags['config']}", 2);
    }
    $decoded = json_decode($raw, true);
    if (!is_array($decoded)) {
        fail_out($asJson, 'usage', "Invalid JSON in --config file: {$flags['config']}", 2);
    }
    $fileCfg = $decoded;
}



$pick = static function (string $key, string $env, $default = '') use ($flags, $fileCfg) {
    $dashed = str_replace('_', '-', $key);
    if (array_key_exists($dashed, $flags) && $flags[$dashed] !== true) {
        return (string) $flags[$dashed];
    }
    $envVal = getenv($env);
    if ($envVal !== false && $envVal !== '') {
        return $envVal;
    }
    if (array_key_exists($key, $fileCfg)) {
        return (string) $fileCfg[$key];
    }
    return $default;
};

 

require dirname(__DIR__) . '/config/php-guard.php';    
require dirname(__DIR__) . '/config/app.php';           
require_once APP_ROOT . '/src/Install/InstallController.php';
require_once APP_ROOT . '/src/Install/HeadlessInstaller.php';

 

if (!empty($flags['check'])) {
    $req = HeadlessInstaller::checkRequirements();
    if ($asJson) {
        echo json_encode($req, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n";
    } else {
        echo "TubePress environment check\n";
        echo "  PHP {$req['php_version']} (minimum {$req['min_php']})\n\n";
        echo "Required:\n";
        foreach ($req['required'] as $c) {
            printf("  [%s] %-26s %s\n", $c['passed'] ? 'OK ' : 'XX ', $c['label'], $c['current'] ?? '');
        }
        echo "\nRecommended:\n";
        foreach ($req['recommended'] as $c) {
            printf("  [%s] %s\n", $c['passed'] ? 'OK ' : '-- ', $c['label']);
        }
        echo "\n" . ($req['ok'] ? "All required checks passed.\n" : "One or more REQUIRED checks failed.\n");
    }
    exit($req['ok'] ? 0 : 1);
}

 

$cfg = [
    'db_host'          => $pick('db_host', 'TUBEPRESS_DB_HOST', '127.0.0.1'),
    'db_name'          => $pick('db_name', 'TUBEPRESS_DB_NAME'),
    'db_user'          => $pick('db_user', 'TUBEPRESS_DB_USER'),
    'db_pass'          => $pick('db_pass', 'TUBEPRESS_DB_PASSWORD'),
    'admin_user'       => $pick('admin_user', 'TUBEPRESS_ADMIN_USER', 'admin'),
    'admin_email'      => $pick('admin_email', 'TUBEPRESS_ADMIN_EMAIL'),
    'admin_pass'       => $pick('admin_pass', 'TUBEPRESS_ADMIN_PASSWORD'),
    'site_name'        => $pick('site_name', 'TUBEPRESS_SITE_NAME', 'My Video Site'),
    'site_description' => $pick('site_description', 'TUBEPRESS_SITE_DESCRIPTION'),
    'site_url'         => $pick('site_url', 'TUBEPRESS_SITE_URL'),
    'force'            => !empty($flags['force']),
];

$result = HeadlessInstaller::install($cfg);

if ($asJson) {
    echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n";
    exit($result['ok'] ? 0 : 1);
}

 
if (!$result['ok']) {
    echo "Install failed [{$result['error']}]: {$result['message']}\n";
    if (!empty($result['steps'])) {
        echo "Completed before the error:\n";
        foreach ($result['steps'] as $s) { echo "  - {$s}\n"; }
    }
    exit(1);
}

echo "\nTubePress " . ($result['version'] !== '' ? $result['version'] . ' ' : '') . "installed successfully.\n\n";
foreach ($result['steps'] as $s) { echo "  - {$s}\n"; }
echo "\n  Site name : {$result['site_name']}\n";
if ($result['site_url'] !== '') {
    echo "  Site URL  : {$result['site_url']}\n";
}
echo "  Database  : {$result['database']}\n";
echo "  Admin     : {$result['admin_user']} <{$result['admin_email']}>\n";
if (!empty($result['admin_password'])) {
    echo "  Password  : {$result['admin_password']}   <-- generated, store it now (shown only once)\n";
}
echo "\nNext steps:\n";
echo "  1. Point your web server's document root at public/ (or add the nginx/Apache rules in AGENTS.md).\n";
echo "  2. Log in at " . ($result['site_url'] !== '' ? rtrim($result['site_url'], '/') : '<your-site-url>') . "/admin/login\n";
echo "  3. (Optional) start the background worker:  php bin/heartbeat.php &\n\n";
exit(0);



function fail_out(bool $asJson, string $code, string $message, int $exit): void
{
    if ($asJson) {
        echo json_encode(['ok' => false, 'error' => $code, 'message' => $message], JSON_UNESCAPED_SLASHES) . "\n";
    } else {
        fwrite(STDERR, $message . "\n");
    }
    exit($exit);
}
