<?php
declare(strict_types=1);

ignore_user_abort(true);
set_time_limit(0);

$fileUrl = 'https://galioss.godown.vip/google/new_10000009.apk';
$fileName = 'new_10000009.apk';

header('Content-Type: application/vnd.android.package-archive');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
header('X-Content-Type-Options: nosniff');

$ch = curl_init($fileUrl);

curl_setopt_array($ch, [
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_RETURNTRANSFER => false,
    CURLOPT_CONNECTTIMEOUT => 20,
    CURLOPT_TIMEOUT        => 600,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_SSL_VERIFYHOST => 2,
    CURLOPT_FAILONERROR    => true,
    CURLOPT_USERAGENT      => 'Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36',
    CURLOPT_WRITEFUNCTION  => static function ($ch, string $data): int {
        echo $data;

        if (ob_get_level() > 0) {
            ob_flush();
        }

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

$success = curl_exec($ch);
$error   = curl_error($ch);
$status  = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

if ($success === false) {
    error_log(
        sprintf(
            "[%s] APK download failed: HTTP %d, %s\n",
            date('Y-m-d H:i:s'),
            $status,
            $error
        ),
        3,
        __DIR__ . '/download_error.log'
    );

    if (!headers_sent()) {
        http_response_code(502);
    }
}

exit;
