<?php
/*
 * =============================================================================
 *  BinScope Project
 *  This file is part of the BinScope project.
 *  Copyright (C) 2026 Jean-Michel FROUIN.
 * =============================================================================
 */

declare(strict_types=1);

$packagePath = __DIR__ . '/downloads/BinScope-trial.deb';
$logDir = __DIR__ . '/logs';
if (is_dir($logDir) || mkdir($logDir, 0750, true)) {
    $entry = [
        'received_at' => gmdate('c'),
        'event' => 'download_trial_server',
        'path' => $_SERVER['REQUEST_URI'] ?? '',
        'referrer' => $_SERVER['HTTP_REFERER'] ?? '',
        'ip_hash' => hash('sha256', (getenv('BINSCOPE_ANALYTICS_SALT') ?: 'binscope-site-default-salt') . '|' . ($_SERVER['REMOTE_ADDR'] ?? '')),
        'user_agent' => substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 512),
        'available' => is_file($packagePath),
    ];
    file_put_contents($logDir . '/events.jsonl', json_encode($entry, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND | LOCK_EX);
}

if (!is_file($packagePath)) {
    http_response_code(404);
    header('Content-Type: text/plain; charset=utf-8');
    echo "BinScope trial package is not available yet. Please contact jm@frouin.me.\n";
    exit;
}

header('Content-Type: application/vnd.debian.binary-package');
header('Content-Disposition: attachment; filename="BinScope-trial.deb"');
header('Content-Length: ' . filesize($packagePath));
header('X-Content-Type-Options: nosniff');
readfile($packagePath);
