#!/usr/bin/env php
<?php
/**
 * CLI runner for the Server Admin > Disk Usage page snapshot.
 *
 * Cron entry (installed by setup.sh):
 *   0 *\/6 * * * /usr/bin/php /root/whp/scripts/disk-usage-snapshot.php
 *
 * Also called synchronously from api/disk-usage.php?action=refresh when
 * root clicks "Refresh now". The shared library lives in
 * /docker/whp/web/libs/disk_usage_snapshot.php so both paths stay in sync.
 */

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

$start = microtime(true);

try {
    $mysql = new mysqlmgmt();
    $db = $mysql->getMySQLConnection();
    if (!$db) {
        fwrite(STDERR, "MySQL connection failed\n");
        exit(1);
    }
    $db->query("USE whp");

    $payload = whp_du_collect_snapshot();
    $duration_ms = (int) round((microtime(true) - $start) * 1000);
    whp_du_save_snapshot($db, $payload, $duration_ms);

    echo "Snapshot taken in {$duration_ms}ms — "
       . count($payload['users']) . " users, "
       . count($payload['services']) . " services, "
       . count($payload['docker']['images']) . " images, "
       . count($payload['cleanup_candidates']) . " cleanup candidates.\n";
} catch (\Throwable $e) {
    fwrite(STDERR, "Snapshot failed: " . $e->getMessage() . "\n");
    exit(1);
}
