<?php
declare(strict_types=1);

use SafeTun\Backend\Config\ConfigValidator;
use SafeTun\Backend\Config\LiteralConfigParser;
use SafeTun\Backend\Storage\NonceStore;
use SafeTun\Backend\Storage\RateLimiter;
use SafeTun\Backend\Storage\AuditLogger;

require dirname(__DIR__) . '/src/autoload.php';

$serverArguments = $_SERVER['argv'] ?? null;
if (!is_array($serverArguments)) {
    fwrite(STDERR, "This command must run from a CLI that provides argv.\n");
    exit(2);
}
$arguments = [];
foreach ($serverArguments as $serverArgument) {
    if (!is_string($serverArgument)) {
        fwrite(STDERR, "Invalid CLI argument vector.\n");
        exit(2);
    }
    $arguments[] = $serverArgument;
}
if (count($arguments) !== 2) {
    fwrite(STDERR, "Usage: php safetun-cleanup.php /path/config.php\n");
    exit(2);
}
try {
    $parsed = (new LiteralConfigParser())->parseFile($arguments[1]);
    $validated = (new ConfigValidator())->validate($parsed, $arguments[1]);
    $cutoff = time() - ($validated->values['runtime']['retention_days'] * 86400);
    $nonces = (new NonceStore($validated->values['runtime']['nonce_dir']))->cleanup($cutoff, 5000);
    $rates = (new RateLimiter($validated->values['runtime']['rate_limit_dir']))->cleanup($cutoff, 5000);
    $logs = (new AuditLogger($validated->values['runtime']['audit_log_dir']))->cleanup($cutoff, 1000);
    echo "Removed {$nonces} nonce records, {$rates} rate-limit records, and {$logs} audit logs.\n";
    exit(0);
} catch (Throwable $exception) {
    fwrite(STDERR, "Cleanup failed safely: {$exception->getMessage()}\n");
    exit(1);
}
