<?php
declare(strict_types=1);

/**
 * Raytunnel.php
 * Faithful PHP port of Raytunnel.py
 * Requires: PHP 8+, curl, openssl, zlib
 */

const CERT_HEX = '3082058930820371a003020102021500d78baccb13e54cd0b7000b95e5fa00c60cade623300d06092a864886f70d01010b05003074310b3009060355040613025553311330110603550408130a43616c69666f726e6961311630140603550407130d4d6f756e7461696e205669657731143012060355040a130b476f6f676c6520496e632e3110300e060355040b1307416e64726f69643110300e06035504031307416e64726f69643020170d3233303630343037343132345a180f32303533303630343037343132345a3074310b3009060355040613025553311330110603550408130a43616c69666f726e6961311630140603550407130d4d6f756e7461696e205669657731143012060355040a130b476f6f676c6520496e632e3110300e060355040b1307416e64726f69643110300e06035504031307416e64726f696430820222300d06092a864886f70d01010105000382020f003082020a0282020100a2ebfd6b123b2f0a175f5498cacb9ff13e5715d75f5f6ad51a34ed163d0a2df13bf3163a986616a1d5f357a4825053eb00dd43958c14257be3bc8bd8e02364ccc84638f40c918516e03d674da151afaf379b75981865353432d9e77cee514eb4d5f47e33bd3bb23c322190bec88c5c03dfb34ed956e986d1262699a4081463ff5dc0ede81b4b77a1bc02666849b408660bf2cfec2573ebbc07f61c3a5dd5a9e637f5e3903db155cbfdd85d7a17d4844c4afda51ae4ab4c0b40856831d7be2072f79b5d86e16fe6e00a865eaccd76ac6b5e992c89f9e2b18f8369108f56745e65c765b7c36cf1c34f407bf68dbc8bdcb2c2922aaf225046b9af7688d9b00eaf8cc389c5f1b7703191ee8256fad9aec4fa928241c3998bfa1d91d47c984e4676212342e2d8197146342aa8bc17bb97440fabf5ea3488dc06662733a2411c10c3a1c35420937e52ccbcf4585478ced9f122c1a9d37094bae1d3f6435796073f4e96b831419a55cead4a93cc685692331735b17693edb741c0946539b626127696b182879401a19a1f31edc8790827656c65cbcb4221217da1e4e8773b5ed9349ae2fc52f38f7ddc54267a961519b9943a91028fd77e898c1e07793358fd5d72ff7eee7c593166fea3f3be9e44c256e20862b5fe97e3f402787fc6a5161a99cf47d54c88f4ebdcade6265b6ac59e670d6384837be7db6619fc462e177e2cf2e8c3c50203010001a310300e300c0603551d13040530030101ff300d06092a864886f70d01010b050003820201004755f8dfa1f70fb049a497ac98b21d3ac2b981db0f78c7ae67477fe6d897c32e312799a7830adcb51507814e3a849aaa98704ed9dfd545ff31bde6412ac4bc846146f5d405c8838272cb3075ec219fba07191375aa1724de4b58e01ac40787045d8e32d026f6f7d908954a3190697cc1453831a3695b789b55eaeede354f5f6cef88a5841eda81bd03e3909d4b315857f9fa173dfc655c9090501acbb136a07707d536a0db7510888a7dc084008a2c84326fc805d50249fcc177bb4168ff29cea3f8f61c2d77e4f7ecf45f886c50558bba554c017c646c43bdeee89ef0917b9de1d9a4df78bee630bf931bd4b3f61d18ce402409889f5ddd375ca00196bd8856bbf7501682f33ac8a2c58d63e34a16723986de25857014d98567aff8d2d558265b4711bb4e7206fb41b2bbc1b5292cb8e36c2e5ce9f24c61b39d11d79b3b80c0d5d3589c331174bdf5342b214278b389d1b75ea5d9349ac333d52c78a1b9a4808fcfe9dd8b6ae0e45b2fc5fad939832a08fb0a52f1f462abb5dfc1298f7e64a291f3a62b599af3905d3f46a82d7cd66958cf82be712015abc64746c56c7704bb7ee8295cf5284188a52b0755d04388d51056c793b0c36c819f62ff59ded86e70d1aefb82160a05e6af1d121ea4e24a877364c17ca9abe180344edab9d2fa06adec4712c1602d35e675f8dc614655916ab34d518c9f283f7111448ca167a17759';
const PACKAGE = 'com.fast.vpn.v2ray.raytunnelvpn';
const API_URL = 'https://d3pwd137ql21v4.cloudfront.net/api/v1/apps/app-data';

const HEADERS = [
    'authorization' => 'ApiKey d7e8f27b-3121-404b-9c07-0b4cc6503722',
    'v' => '700.7',
    'Connection' => 'keep-alive',
    'Upgrade-Insecure-Requests' => '1',
    'Accept-Encoding' => 'gzip',
    'User-Agent' => 'okhttp/5.4.0'
];

function key_bytes(): string
{
    // Python: sha256(CERT_HEX.encode("latin-1") + PACKAGE.encode()).digest()
    return hash('sha256', CERT_HEX . PACKAGE, true);
}

function increment_counter(string $counter): string
{
    // 128-bit big-endian increment, exactly matching Python's integer counter.
    for ($i = 15; $i >= 0; --$i) {
        $n = ord($counter[$i]);
        if ($n === 255) {
            $counter[$i] = "\x00";
        } else {
            $counter[$i] = chr($n + 1);
            break;
        }
    }
    return $counter;
}

function zlib_decompress_47(string $data): string
{
    // Python zlib.decompress(data, 47) accepts gzip/zlib wrappers.
    $out = @gzdecode($data);
    if ($out !== false) return $out;

    $out = @zlib_decode($data);
    if ($out !== false) return $out;

    $out = @gzuncompress($data);
    if ($out !== false) return $out;

    throw new RuntimeException('gzip/zlib decompression failed');
}

function decrypt_data(string $b64): string
{
    $raw = base64_decode($b64, true);
    if ($raw === false) {
        throw new RuntimeException('Invalid base64 payload');
    }
    if (strlen($raw) < 16) {
        throw new RuntimeException('Encrypted payload is shorter than 16-byte IV');
    }

    $counter = substr($raw, 0, 16);
    $ct = substr($raw, 16);
    $key = key_bytes();
    $pt = '';

    // Match the Python implementation exactly:
    // AES-ECB(counter) -> keystream; XOR with ciphertext; increment 128-bit BE counter.
    for ($offset = 0, $len = strlen($ct); $offset < $len; $offset += 16) {
        $block = substr($ct, $offset, 16);
        $ks = openssl_encrypt(
            $counter,
            'aes-256-ecb',
            $key,
            OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING
        );
        if ($ks === false || strlen($ks) !== 16) {
            throw new RuntimeException('AES-256-ECB keystream generation failed');
        }

        $pt .= $block ^ substr($ks, 0, strlen($block));
        $counter = increment_counter($counter);
    }

    if (strlen($pt) >= 2 && substr($pt, 0, 2) === "\x1f\x8b") {
        $pt = zlib_decompress_47($pt);
    }

    if (@preg_match('//u', $pt) !== 1) {
        throw new RuntimeException('Decrypted plaintext is not valid UTF-8');
    }
    return $pt;
}

function etag_path(): string
{
    return __DIR__ . '/.last_etag';
}

function fetch_data(string $etag = '', bool $force = false): array
{
    $headers = [];
    foreach (HEADERS as $k => $v) {
        $headers[] = $k . ': ' . $v;
    }
    if ($etag !== '' && !$force) {
        $headers[] = 'If-None-Match: ' . $etag;
    }

    $ch = curl_init(API_URL);
    if ($ch === false) {
        throw new RuntimeException('curl_init failed');
    }

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HEADER => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_CONNECTTIMEOUT => 15,
        // Keep the response bytes raw. We handle gzip exactly as the Python code does.
        CURLOPT_ENCODING => 'identity',
    ]);

    $response = curl_exec($ch);
    if ($response === false) {
        $err = curl_error($ch);
        curl_close($ch);
        throw new RuntimeException('HTTP request failed: ' . $err);
    }

    $code = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    $headerSize = (int)curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    curl_close($ch);

    $headerBlob = substr($response, 0, $headerSize);
    $body = substr($response, $headerSize);

    $rh = [];
    // Header blob may contain multiple HTTP header sections (e.g. 100/redirect/proxy).
    foreach (preg_split("/\r\n|\n|\r/", $headerBlob) as $line) {
        $pos = strpos($line, ':');
        if ($pos === false) continue;
        $name = trim(substr($line, 0, $pos));
        $value = trim(substr($line, $pos + 1));
        if ($name !== '') {
            $rh[strtolower($name)] = $value;
        }
    }

    if ($code !== 304 && isset($rh['etag'])) {
        file_put_contents(etag_path(), $rh['etag']);
    }

    return [$code, $body, $rh];
}

function gz_decompress_response(string $body): string
{
    $out = @gzdecode($body);
    if ($out !== false) return $out;

    $out = @zlib_decode($body);
    if ($out !== false) return $out;

    throw new RuntimeException('HTTP gzip decompression failed');
}

function tls_sname(array $ss): string
{
    return (string)($ss['tlsSettings']['serverName'] ?? '-');
}


function fix_finalmask_for_xray_2659(array &$cfg): void
{
    if (
        !isset($cfg['outbounds']) ||
        !is_array($cfg['outbounds'])
    ) {
        return;
    }

    foreach ($cfg['outbounds'] as &$outbound) {

        if (
            !isset($outbound['streamSettings']['finalmask']['tcp']) ||
            !is_array($outbound['streamSettings']['finalmask']['tcp'])
        ) {
            continue;
        }

        foreach (
            $outbound['streamSettings']['finalmask']['tcp']
            as &$mask
        ) {
            if (
                ($mask['type'] ?? '') !== 'fragment' ||
                !isset($mask['settings']) ||
                !is_array($mask['settings'])
            ) {
                continue;
            }

            $settings =& $mask['settings'];

            /*
             * Xray-core 26.5.9 compatibility:
             *
             * lengths -> length
             * delays  -> delay
             */

            if (
                isset($settings['lengths']) &&
                is_array($settings['lengths']) &&
                count($settings['lengths']) > 0
            ) {
                $v = $settings['lengths'];

                /*
                 * Raytunnel examples:
                 *
                 * ["0","104","1"] -> "1-104"
                 * ["114","1"]     -> "1-114"
                 */

                $nums = [];

                foreach ($v as $x) {
                    if (is_numeric($x)) {
                        $n = (int)$x;

                        if ($n > 0) {
                            $nums[] = $n;
                        }
                    }
                }

                if ($nums) {
                    $min = min($nums);
                    $max = max($nums);

                    $settings['length'] =
                        ($min === $max)
                        ? (string)$min
                        : $min . '-' . $max;
                }

                unset($settings['lengths']);
            }

            if (
                isset($settings['delays']) &&
                is_array($settings['delays']) &&
                count($settings['delays']) > 0
            ) {
                $v = $settings['delays'];

                if (count($v) === 1) {
                    $settings['delay'] = (string)$v[0];
                } else {
                    $nums = [];

                    foreach ($v as $x) {
                        if (is_numeric($x)) {
                            $nums[] = (int)$x;
                        }
                    }

                    if ($nums) {
                        $min = min($nums);
                        $max = max($nums);

                        $settings['delay'] =
                            ($min === $max)
                            ? (string)$min
                            : $min . '-' . $max;
                    }
                }

                unset($settings['delays']);
            }
        }

        unset($mask);
    }

    unset($outbound);
}

function main(): void
{
    [$code, $body, $rh] = fetch_data('', true);

    if ($code < 200 || $code >= 300) {
        throw new RuntimeException("Unexpected HTTP status: $code");
    }

    if (
        strlen($body) >= 2 &&
        substr($body, 0, 2) === "\x1f\x8b"
    ) {
        $body = gz_decompress_response($body);
    }

    $encrypted = json_decode(
        $body,
        true,
        512,
        JSON_THROW_ON_ERROR
    );

    if (
        !is_array($encrypted) ||
        !isset($encrypted['data']) ||
        !is_string($encrypted['data'])
    ) {
        throw new RuntimeException(
            'Payload does not contain encrypted data'
        );
    }

    $plain = decrypt_data($encrypted['data']);

    // ---------------- MODE ----------------

    if (isset($_GET['smart'])) {
        $mode = 'smart';
    } elseif (isset($_GET['normal'])) {
        $mode = 'normal';
    } else {
        // بدون پارامتر = کل JSON دیکریپت شده
        echo $plain;
        return;
    }

    $decoded = json_decode(
        $plain,
        true,
        512,
        JSON_THROW_ON_ERROR
    );

    $items = $decoded['configs'][$mode] ?? [];

    if (!is_array($items)) {
        return;
    }

    $configs = [];

    foreach ($items as $item) {
        if (
            is_array($item) &&
            isset($item['config']) &&
            is_string($item['config'])
        ) {
            $config = trim($item['config']);

            if ($config !== '') {

                $cfg = json_decode(
                    $config,
                    false,
                    512,
                    JSON_THROW_ON_ERROR
                );

                if (is_object($cfg)) {

                    /*
                     * Convert to array only inside the FinalMask fixer,
                     * then restore the original JSON object structure.
                     *
                     * Empty JSON objects such as settings:{} must NOT
                     * become settings:[].
                     */

                    $tmp = json_decode(
                        json_encode(
                            $cfg,
                            JSON_UNESCAPED_UNICODE |
                            JSON_UNESCAPED_SLASHES |
                            JSON_THROW_ON_ERROR
                        ),
                        true,
                        512,
                        JSON_THROW_ON_ERROR
                    );

                    fix_finalmask_for_xray_2659($tmp);

                    /*
                     * Explicitly restore fields which v2rayNG requires
                     * to be JSON objects when empty.
                     */
                    if (isset($tmp['inbounds']) && is_array($tmp['inbounds'])) {
                        foreach ($tmp['inbounds'] as &$inbound) {
                            if (
                                array_key_exists('settings', $inbound) &&
                                is_array($inbound['settings']) &&
                                count($inbound['settings']) === 0
                            ) {
                                $inbound['settings'] = new stdClass();
                            }
                        }
                        unset($inbound);
                    }

                    if (isset($tmp['outbounds']) && is_array($tmp['outbounds'])) {
                        foreach ($tmp['outbounds'] as &$outbound) {
                            if (
                                array_key_exists('settings', $outbound) &&
                                is_array($outbound['settings']) &&
                                count($outbound['settings']) === 0
                            ) {
                                $outbound['settings'] = new stdClass();
                            }
                        }
                        unset($outbound);
                    }

                    $config = json_encode(
                        $tmp,
                        JSON_UNESCAPED_UNICODE |
                        JSON_UNESCAPED_SLASHES |
                        JSON_THROW_ON_ERROR
                    );
                }

                // هر کانفیگ دقیقاً یک خط
                $configs[] = str_replace(
                    ["\r", "\n"],
                    '',
                    $config
                );
            }
        }
    }

    if (!$configs) {
        return;
    }

    // ---------------- SINGLE / ROUND ROBIN ----------------

    $single =
        isset($_GET[$mode]) &&
        (string)$_GET[$mode] === '1';

    if ($single) {

        /*
         * فایل counter داخل /tmp قرار می‌گیرد تا
         * روی PHP-FPM/هاست نیز writable باشد.
         */
        $counterFile =
            sys_get_temp_dir() .
            '/raytunnel_' .
            $mode .
            '_counter.txt';

        $fp = fopen($counterFile, 'c+');

        if ($fp === false) {
            throw new RuntimeException(
                'Cannot open counter file'
            );
        }

        if (!flock($fp, LOCK_EX)) {
            fclose($fp);

            throw new RuntimeException(
                'Cannot lock counter file'
            );
        }

        rewind($fp);

        $raw = trim(
            (string)stream_get_contents($fp)
        );

        $index = ctype_digit($raw)
            ? (int)$raw
            : 0;

        $count = count($configs);

        // حتی اگر تعداد کانفیگ‌ها تغییر کند
        $index %= $count;

        // فقط همین یک کانفیگ
        echo $configs[$index];

        // کانفیگ بعدی
        $next = ($index + 1) % $count;

        rewind($fp);
        ftruncate($fp, 0);
        fwrite($fp, (string)$next);
        fflush($fp);

        flock($fp, LOCK_UN);
        fclose($fp);

        return;
    }

    // ---------------- ALL ----------------

    echo implode("\n", $configs);
}

try {
    main();
} catch (Throwable $e) {
    error_log('Raytunnel: ' . $e->getMessage());
    exit(1);
}
