#!/usr/bin/env php
<?php
declare(strict_types=1);

/**
 * Purge stale remote-access sessions (cron: hourly).
 * Usage: php scripts/purge_remote_access.php [--hours=24] [--no-prune-wg]
 */
require_once __DIR__ . '/../src/bootstrap.php';
require_once __DIR__ . '/../src/RemoteAccessRepository.php';
require_once __DIR__ . '/../src/WireGuardPeerProvisioner.php';

$hours = 24;
$pruneWg = true;
foreach ($argv as $arg) {
    if (str_starts_with($arg, '--hours=')) {
        $hours = max(1, (int) substr($arg, 8));
    } elseif ($arg === '--no-prune-wg') {
        $pruneWg = false;
    }
}

RemoteAccessRepository::ensureSchema();
$n = RemoteAccessRepository::purgeStale($hours);
fwrite(STDOUT, "purged_sessions={$n}\n");

if ($pruneWg) {
    $pruned = RemoteAccessRepository::pruneOrphanWireGuardPeers(false);
    fwrite(STDOUT, 'pruned_wg_peers=' . count($pruned) . "\n");
}
