<?php
declare(strict_types=1);

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

$socket = '/run/backupper/backupper.sock';
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$path = $_GET['path'] ?? '/v1/health';

if (!preg_match('#^/v1/[A-Za-z0-9_./?=&%:-]*$#', $path) || str_contains($path, '..')) {
    http_response_code(400);
    echo json_encode(['error' => 'invalid API path']);
    exit;
}

if ($method !== 'GET') {
    $provided = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
    $runtime = @parse_ini_file('/var/local/emhttp/var.ini') ?: [];
    $expected = $runtime['csrf_token'] ?? '';
    if ($expected === '' || !hash_equals((string)$expected, (string)$provided)) {
        http_response_code(403);
        echo json_encode(['error' => 'invalid CSRF token']);
        exit;
    }
}

if (!file_exists($socket)) {
    http_response_code(503);
    echo json_encode(['error' => 'Backupper daemon is not running']);
    exit;
}

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_UNIX_SOCKET_PATH => $socket,
    CURLOPT_URL => 'http://localhost' . $path,
    CURLOPT_CUSTOMREQUEST => $method,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 3,
    CURLOPT_TIMEOUT => 310,
    CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
]);

$body = file_get_contents('php://input');
if ($method !== 'GET' && $body !== false && $body !== '') {
    curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
}

$response = curl_exec($curl);
$status = (int)curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
$error = curl_error($curl);
curl_close($curl);

if ($response === false) {
    http_response_code(502);
    echo json_encode(['error' => 'Daemon connection failed: ' . $error]);
    exit;
}

http_response_code($status > 0 ? $status : 502);
echo $response;
