<?php
/**
 * One-shot backfill: create the default daily backup schedule for every
 * existing WHP user that doesn't already have at least one schedule row.
 *
 * Run automatically by update.sh post-update; also safe to invoke manually:
 *   php scripts/updates/$VERSION/backfill-default-backup-schedules.php
 *
 * Idempotent — BackupDefaults::createForUser checks for an existing schedule
 * and skips users that already have one. Re-running the script is harmless.
 */

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

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

// Pull the WHP-managed user list. user_passwords is the canonical roster of
// hosting-panel accounts (created via UserMgmt::create_new_user). Skipping
// 'root' so we don't create user-scoped backup schedules for the operator.
$stmt = $db->prepare("SELECT username FROM user_passwords WHERE username != 'root'");
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_COLUMN);

$totalUsers     = count($users);
$totalCreated   = 0;
$totalSkipped   = 0;
$noTargetCount  = 0;

echo "Backfilling default backup schedules for {$totalUsers} users...\n";

foreach ($users as $username) {
    try {
        $result = \WHPBackup\BackupDefaults::createForUser($db, $username);
        if ($result['skipped']) {
            $totalSkipped++;
            if (($result['reason'] ?? '') === 'no default target') {
                $noTargetCount++;
            }
            echo "  [skip] {$username}: {$result['reason']}\n";
        } else {
            $totalCreated += $result['created'];
            echo "  [ok]   {$username}: created {$result['created']} schedules\n";
        }
    } catch (\Throwable $e) {
        fwrite(STDERR, "  [err]  {$username}: " . $e->getMessage() . "\n");
    }
}

echo "\nDone. Users processed: {$totalUsers}; schedule rows created: {$totalCreated}; skipped: {$totalSkipped}";
if ($noTargetCount > 0) {
    echo " (of which {$noTargetCount} skipped due to no default backup target — set is_global=1 on a backup_targets row to fix)";
}
echo "\n";
