<?php
/**
 * SSL Renewal Orchestrator Cron Driver
 *
 * Wraps ssl_renewal_orchestrator::runSweep() for cron invocation. Lives at the
 * top level of scripts/ (per build-release.sh: top-level scripts ship via
 * `git pull` to /root/whp/, not via the release tarball).
 *
 * The orchestrator is gated by whp.settings.ssl_orchestrator_enabled. While
 * the flag is 0, this driver logs "skipped, orchestrator disabled" and exits.
 * Flip the flag to 1 once the backfill has been audited.
 *
 * Cron entry (installed by setup-ssl-renewal-orchestrator-cron.sh):
 *   *\/30 * * * * /usr/bin/flock -n /run/whp-ssl-orchestrator.lock \
 *                /usr/bin/timeout 240 /usr/bin/php \
 *                /root/whp/scripts/ssl-renewal-orchestrator-cron.php \
 *                >> /var/log/whp-ssl-orchestrator.log 2>&1
 */

require_once('/docker/whp/web/configs/config.php');
require_once('/docker/whp/web/libs/ssl_renewal_orchestrator.php');

$started_at = microtime(true);
$ts = date('Y-m-d H:i:s');

// Master kill switch lives in /docker/whp/settings.json under
// ssl_renewal.orchestrator_enabled. Default false → cron is dormant until
// explicitly flipped after the backfill audit.
$ssl_settings = ssl_renewal_orchestrator::loadSslRenewalSettings();
$enabled = (bool)($ssl_settings['orchestrator_enabled'] ?? false);

if (!$enabled) {
    fwrite(STDOUT, "[$ts] ssl-orchestrator-cron: skipped (settings.json ssl_renewal.orchestrator_enabled=false)\n");
    exit(0);
}

try {
    // Orchestrator constructs its own PDO when called without a $db arg.
    $orch = new ssl_renewal_orchestrator();
    $counts = $orch->runSweep(50);
    $elapsed = round(microtime(true) - $started_at, 2);
    fwrite(STDOUT, "[$ts] ssl-orchestrator-cron: " . json_encode($counts) . " elapsed={$elapsed}s\n");
    // Non-zero exit only on exception (caught below); transient failures are
    // counted in the JSON but don't fail the cron itself.
    exit(0);
} catch (Throwable $e) {
    $elapsed = round(microtime(true) - $started_at, 2);
    fwrite(STDERR, "[$ts] ssl-orchestrator-cron: FATAL " . $e->getMessage() . " elapsed={$elapsed}s\n");
    exit(1);
}
