<?php
require_once __DIR__ . '/includes/stream_lib.php';

if (session_status() === PHP_SESSION_ACTIVE) {
    session_write_close();
}

@set_time_limit(0);
ignore_user_abort(true);

while (ob_get_level() > 0) {
    @ob_end_clean();
}

if (function_exists('apache_setenv')) {
    @apache_setenv('no-gzip', '1');
}

@ini_set('zlib.output_compression', '0');
@ini_set('output_buffering', '0');
@ini_set('implicit_flush', '1');

$cfg = smurf_get_stream_config();
$streamUrl = trim((string)($cfg['listen_url'] ?? ''));

if ($streamUrl === '') {
    http_response_code(503);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Stream URL not configured.';
    exit;
}

header('Content-Type: audio/mpeg');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
header('Access-Control-Allow-Origin: *');
header('X-Accel-Buffering: no');

$sentContentType = false;

$ch = curl_init($streamUrl);

curl_setopt_array($ch, [
    CURLOPT_FOLLOWLOCATION   => true,
    CURLOPT_RETURNTRANSFER   => false,
    CURLOPT_HEADER           => false,
    CURLOPT_CONNECTTIMEOUT   => 10,
    CURLOPT_TIMEOUT          => 0,
    CURLOPT_LOW_SPEED_LIMIT  => 1,
    CURLOPT_LOW_SPEED_TIME   => 20,
    CURLOPT_BUFFERSIZE       => 32768,
    CURLOPT_SSL_VERIFYPEER   => false,
    CURLOPT_SSL_VERIFYHOST   => false,
    CURLOPT_USERAGENT        => 'Mozilla/5.0 Radio Galaxy FXRadioProxy/1.0',
    CURLOPT_HTTPHEADER       => [
        'Accept: */*',
        'Connection: keep-alive',
        'Cache-Control: no-cache',
        'Pragma: no-cache',
    ],
    CURLOPT_HEADERFUNCTION   => function ($ch, $header) use (&$sentContentType) {
        $len = strlen($header);
        $parts = explode(':', $header, 2);

        if (count($parts) === 2) {
            $name  = strtolower(trim($parts[0]));
            $value = trim($parts[1]);

            if ($name === 'content-type' && $value !== '' && !$sentContentType && !headers_sent()) {
                header('Content-Type: ' . $value);
                $sentContentType = true;
            }
        }

        return $len;
    },
    CURLOPT_WRITEFUNCTION    => function ($ch, $data) {
        echo $data;

        if (function_exists('ob_flush')) {
            @ob_flush();
        }
        @flush();

        return strlen($data);
    },
]);

$result = curl_exec($ch);

if ($result === false) {
    $err = curl_error($ch);

    if (!headers_sent()) {
        http_response_code(502);
        header('Content-Type: text/plain; charset=utf-8');
    }

    echo 'Proxy stream unavailable.';
    if ($err !== '') {
        echo ' ' . $err;
    }
}

curl_close($ch);