<?php
// Requires PHP cURL; HTTPS-proxy support is a separate libcurl capability.
try {
    $target = getenv('QG_TARGET_URL');
    $proxy = getenv('QUOTAGUARDSTATIC_URL');
    $t = parse_url($target ?: '');
    $p = parse_url($proxy ?: '');
    if (!$t || ($t['scheme'] ?? '') !== 'https' || empty($t['host']) || isset($t['user']) ||
        !$p || !in_array($p['scheme'] ?? '', ['http', 'https'], true) || empty($p['host']) || empty($p['user']) || empty($p['pass'])) {
        throw new Exception('config');
    }
    $token = getenv('DESTINATION_API_TOKEN') ?: '';
    if (preg_match('/[\x00-\x1f\x7f]/', $token) || ($token !== '' && $t['host'] === 'ip.quotaguard.com')) { throw new Exception('config'); }
    if ($p['scheme'] === 'https' && !(curl_version()['features'] & CURL_VERSION_HTTPS_PROXY)) { throw new Exception('proxy TLS unsupported'); }
    $ch = curl_init($target);
    curl_setopt_array($ch, [CURLOPT_PROXY => $proxy, CURLOPT_NOPROXY => '',
        CURLOPT_HTTPPROXYTUNNEL => true, CURLOPT_FOLLOWLOCATION => false,
        CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_HTTPHEADER => $token !== '' ? ['Authorization: Bearer ' . $token] : [],
        CURLOPT_WRITEFUNCTION => static function ($ch, $data) { return strlen($data); }]);
    $ok = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);
    if ($ok === false || $status < 200 || $status >= 300) { throw new Exception('request'); }
    echo "PASS: destination returned a successful HTTP status\n";
} catch (Throwable $e) {
    fwrite(STDERR, "Request failed; check configuration and the guide.\n");
    exit(1);
}
