<?php
declare(strict_types=1);

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

$socket = '/run/urbm/urbm.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 (!file_exists($socket)) {
    http_response_code(503);
    echo json_encode(['error' => 'Der URBM-Daemon läuft nicht']);
    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' => 'Verbindung zum URBM-Daemon fehlgeschlagen: ' . $error]);
    exit;
}

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