<?php
// Target Jenkins backend (tunneled via SSH)
$target = "http://127.0.0.1:8080" . $_SERVER['REQUEST_URI'];

// Initialize cURL
$ch = curl_init($target);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER => true,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false,
    CURLOPT_CUSTOMREQUEST => $_SERVER['REQUEST_METHOD'],
    CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT'] ?? 'PHP-Proxy',
]);

// Forward headers from client
$headers = [];
foreach (getallheaders() as $key => $value) {
    // Skip Host header to avoid conflicts
    if (strcasecmp($key, 'Host') === 0) continue;
    $headers[] = "$key: $value";
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// Forward POST/PUT body if any
if (in_array($_SERVER['REQUEST_METHOD'], ['POST', 'PUT', 'PATCH'])) {
    $input = file_get_contents('php://input');
    curl_setopt($ch, CURLOPT_POSTFIELDS, $input);
}

// Execute
$response = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
curl_close($ch);

// Send headers to browser
foreach (explode("\r\n", $header) as $hdr) {
    if (stripos($hdr, 'Transfer-Encoding:') === 0) continue;
    if (stripos($hdr, 'Content-Length:') === 0) continue;
    if (stripos($hdr, 'Connection:') === 0) continue;
    if (stripos($hdr, 'Location:') === 0) {
        // Re-map redirects back through proxy
        $hdr = preg_replace('#Location:\s*http://127\.0\.0\.1:8080#i', '', $hdr);
    }
    if (!empty($hdr)) header($hdr, false);
}

// Output body
echo $body;
?>
