<?php

declare(strict_types=1);

// Usage (PowerShell):
//   C:\xampp\php\php.exe tools\generate_vapid.php

$baseDir = realpath(__DIR__ . '/..');
if ($baseDir === false) {
    fwrite(STDERR, "Unable to resolve base dir\n");
    exit(1);
}

require_once $baseDir . '/includes/config.php';
require_once $baseDir . '/vendor/autoload.php';

use Minishlink\WebPush\VAPID;

$cur = getenv('OPENSSL_CONF');
if (!is_string($cur) || $cur === '' || !file_exists($cur)) {
    $candidates = [
        'C:\\xampp\\apache\\conf\\openssl.cnf',
        'C:\\xampp\\php\\extras\\openssl\\openssl.cnf',
        'C:\\xampp\\php\\extras\\ssl\\openssl.cnf',
    ];
    foreach ($candidates as $p) {
        if (file_exists($p)) {
            putenv('OPENSSL_CONF=' . $p);
            break;
        }
    }
}

if (!is_dir(DATA_DIR)) {
    mkdir(DATA_DIR, 0777, true);
}

$path = VAPID_KEYS_JSON;
if (file_exists($path)) {
    fwrite(STDERR, "VAPID keys already exist at {$path}\n");
    exit(0);
}

$keys = VAPID::createVapidKeys();
$out = [
    'subject' => defined('VAPID_SUBJECT') ? VAPID_SUBJECT : 'mailto:admin@timezup.local',
    'publicKey' => $keys['publicKey'] ?? '',
    'privateKey' => $keys['privateKey'] ?? '',
    'created_at' => gmdate('c'),
];

file_put_contents($path, json_encode($out, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n");

fwrite(STDOUT, "Created VAPID keys: {$path}\n");
