<?php
/**
 * Disk-cleanup detection + execution. Root-only.
 *
 *   GET  ?action=detect   -> JSON { success, candidates: [{path, size, reason}] }
 *   POST ?action=execute  -> body: { paths: [...] } -> deletes whitelisted paths
 *
 * The user-flow: banner button (or AI Monitor page) opens a modal that
 * calls detect; user reviews and selects items; execute deletes them.
 *
 * Safety rules:
 *  - Whitelisted prefixes only: /var/log, /var/lib/docker/containers,
 *    /docker/users/<u>/<dom>/logs, journalctl rotated archives.
 *  - Whitelisted name patterns only: *.gz, *.[0-9]*, *-json.log (Docker),
 *    or files matching the journal pattern.
 *  - File age > 30 days for rotated archives, >= now for active Docker
 *    json logs (we truncate via `: > path`, not `unlink`).
 *  - Each path is re-validated server-side at execute time -- the JSON
 *    payload from the client is treated as untrusted; we don't trust the
 *    client's "this passed detect" assertion.
 *  - Path traversal blocks: realpath() must stay inside one of the
 *    whitelisted roots after canonicalization.
 */

header('Content-Type: application/json');

if (!defined('AUTH_USER') || AUTH_USER !== 'root') {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'root only']);
    exit;
}
require_once(__DIR__ . "/../libs/disk_cleanup_helpers.php");


$action = $_REQUEST['action'] ?? '';

if ($action === 'detect') {
    echo json_encode([
        'success'    => true,
        'candidates' => detect_cleanup_candidates(),
    ]);
    exit;
}

if ($action === 'execute') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['success' => false, 'error' => 'method not allowed']);
        exit;
    }
    $raw = file_get_contents('php://input');
    $body = json_decode($raw, true);
    $paths = $body['paths'] ?? [];
    if (!is_array($paths) || empty($paths)) {
        echo json_encode(['success' => false, 'error' => 'no paths']);
        exit;
    }
    $result = execute_cleanup($paths);
    echo json_encode($result);
    exit;
}

// Per-row actions called from the Server Admin > Disk Usage page.
// Each one is narrower than execute() and validates the target against
// the same whitelisted-roots check.

if ($action === 'truncate') {
    $body = json_decode(file_get_contents('php://input'), true) ?: [];
    echo json_encode(truncate_active_log($body['path'] ?? ''));
    exit;
}
if ($action === 'clear_rotated') {
    $body = json_decode(file_get_contents('php://input'), true) ?: [];
    echo json_encode(clear_rotated_in_dir($body['path'] ?? ''));
    exit;
}
if ($action === 'safe_clear') {
    $body = json_decode(file_get_contents('php://input'), true) ?: [];
    echo json_encode(safe_clear_directory($body['path'] ?? ''));
    exit;
}
if ($action === 'journal_vacuum') {
    echo json_encode(journal_vacuum());
    exit;
}

if ($action === 'prune_dangling_images') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['success' => false, 'error' => 'method not allowed']);
        exit;
    }
    echo json_encode(start_dangling_prune_job());
    exit;
}

if ($action === 'prune_status') {
    echo json_encode(get_dangling_prune_status());
    exit;
}

http_response_code(400);
echo json_encode(['success' => false, 'error' => 'unknown action']);
exit;

