#!/usr/bin/env bash
# Backfill: create the default daily backup schedule for every existing WHP
# user that doesn't already have one. Idempotent -- BackupDefaults skips users
# that already have a schedule, so re-running on every future update is fine.
#
# Runs during update.sh BEFORE the rsync that copies web-files into
# /docker/whp/web/. So mysqlmgmt / BackupTarget / BackupSchedule already
# exist at /docker/whp/web/libs/ from the previous version, but BackupDefaults
# is brand-new and only present in the tarball. We deliberately load the
# pre-existing libs from the LIVE install (/docker/whp/web/libs/) and load
# only the new BackupDefaults from the tarball, to avoid re-declaring classes
# from two different on-disk paths.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

TARBALL_LIBS="$SCRIPT_DIR/../../../web-files/libs"
LIVE_LIBS="/docker/whp/web/libs"

# Find the new BackupDefaults — prefer live (post-install or manual re-run),
# fall back to the tarball (during the update.sh window before rsync).
if [ -f "$LIVE_LIBS/BackupDefaults.php" ]; then
    BACKUP_DEFAULTS="$LIVE_LIBS/BackupDefaults.php"
elif [ -f "$TARBALL_LIBS/BackupDefaults.php" ]; then
    BACKUP_DEFAULTS="$(cd "$TARBALL_LIBS" && pwd)/BackupDefaults.php"
else
    echo "ERROR: cannot locate BackupDefaults.php in tarball ($TARBALL_LIBS) or live ($LIVE_LIBS)"
    exit 1
fi

echo "Running default-backup-schedule backfill (BackupDefaults=$BACKUP_DEFAULTS)..."

BACKUP_DEFAULTS="$BACKUP_DEFAULTS" php <<'PHPEOF'
<?php
require_once('/docker/whp/web/configs/config.php');
require_once('/docker/whp/web/libs/mysqlmgmt.php');
require_once('/docker/whp/web/libs/BackupTarget.php');
require_once('/docker/whp/web/libs/BackupSchedule.php');
require_once(getenv('BACKUP_DEFAULTS'));

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

$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 " ({$noTargetCount} skipped due to no default backup target -- set is_global=1 on a backup_targets row to enable)";
}
echo "\n";
PHPEOF
