<?php
declare(strict_types=1);

date_default_timezone_set('Asia/Shanghai');

$pkg = $_GET['pkg'] ?? '';

$map = [
    'v1-android' => 'https://gitcode.com/heikewl12/ISF/releases/download/ISF1/Element.apk',
    'v2-android' => 'https://52w1.cn/Xchat.apk',
    'ios-testflight-app' => 'https://apps.apple.com/cn/app/testflight/id899247664',
    'ios-rongxun' => 'https://testflight.apple.com/join/rCm7Qc66',
    'windows' => '',
];

if (!isset($map[$pkg])) {
    http_response_code(404);
    exit('Not Found');
}

$logDir = __DIR__ . '/runtime_logs';
if (!is_dir($logDir)) {
    mkdir($logDir, 0777, true);
}

$ip = $_SERVER['REMOTE_ADDR'] ?? '-';
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '-';
$referer = $_SERVER['HTTP_REFERER'] ?? '-';

file_put_contents(
    $logDir . '/download.log',
    sprintf(
        "[%s] ip=%s pkg=%s referer=%s ua=%s\n",
        date('Y-m-d H:i:s'),
        $ip,
        $pkg,
        $referer,
        $ua
    ),
    FILE_APPEND
);

header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
header('Location: ' . $map[$pkg], true, 302);
exit;
