<?php
// log_rotate.php - Rotate and prune debug_log.txt and backups/sync_log.txt.
// Modes:
//   CLI                : php log_rotate.php
//   Web (token gated)  : log_rotate.php?token=<config.backup_sync.cron_key>
// Safe to run repeatedly. Will NEVER delete anything younger than 90 days.

$isCli = (php_sapi_name() === 'cli');

if (!$isCli) {
    require_once __DIR__ . '/helpers.php';
    $expected = (string) getConfig('backup_sync.cron_key', '');
    $provided = (string) ($_GET['token'] ?? '');
    if ($expected === '' || !hash_equals($expected, $provided)) {
        http_response_code(403);
        header('Content-Type: text/plain');
        die("Forbidden.");
    }
    header('Content-Type: text/plain; charset=utf-8');
}

$logTargets = [
    __DIR__ . '/debug_log.txt',
    __DIR__ . '/backups/sync_log.txt',
];

$archiveDir = __DIR__ . '/backups/archive';
if (!is_dir($archiveDir)) {
    @mkdir($archiveDir, 0750, true);
}

$today = date('Y-m-d');
$pruneBefore = strtotime('-90 days');
$rotated = 0;
$pruned  = 0;

foreach ($logTargets as $path) {
    if (!is_file($path)) {
        echo "skip (missing): $path\n";
        continue;
    }
    // Only rotate if file > 1 MB to avoid creating tiny daily fragments.
    $size = @filesize($path);
    if ($size === false || $size < 1024 * 1024) {
        echo "skip (small " . (int)$size . "B): $path\n";
        continue;
    }
    $basename = basename($path);
    $dest = $archiveDir . '/' . $basename . '.' . $today . '.' . substr(sha1((string)mt_rand()), 0, 6) . '.txt';
    if (@copy($path, $dest)) {
        @file_put_contents($path, ''); // truncate
        $rotated++;
        echo "rotated: $path -> " . basename($dest) . "\n";
    } else {
        echo "FAILED copy: $path\n";
    }
}

// Prune archive files older than 90 days
$dh = @opendir($archiveDir);
if ($dh) {
    while (($f = readdir($dh)) !== false) {
        if ($f === '.' || $f === '..') continue;
        $full = $archiveDir . '/' . $f;
        if (!is_file($full)) continue;
        $mtime = @filemtime($full);
        if ($mtime !== false && $mtime < $pruneBefore) {
            if (@unlink($full)) {
                $pruned++;
                echo "pruned (>90d): $f\n";
            }
        }
    }
    closedir($dh);
}

echo "\nDone. Rotated: $rotated  Pruned: $pruned\n";
