<?php
/**
 * Émet une nouvelle license dans la base. La clé est imprimée en clair sur stdout
 * (à transmettre au client par canal sécurisé). Aucune trace en clair côté serveur :
 * la base ne stocke que la clé via UNIQUE pour la lookup constant-time.
 *
 * Usage (SSH OVH) :
 *   php tools/issue-license.php "ACME Corp" 2026-12-31 [maxMachines=1]
 */
declare(strict_types=1);

require dirname(__DIR__) . '/api/lib/Db.php';
$config = require dirname(__DIR__) . '/api/config.php';

if ($argc < 3) {
    fwrite(STDERR, "Usage: php tools/issue-license.php \"<owner_name>\" <YYYY-MM-DD entitlement_until> [max_machines=1]\n");
    exit(1);
}

$owner = $argv[1];
$until = $argv[2];
$maxMachines = (int)($argv[3] ?? 1);

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $until)) {
    fwrite(STDERR, "entitlement_until must be YYYY-MM-DD\n"); exit(2);
}

$db = \PSLauncher\Db::get($config);

// Génère une clé du type PRSRV-XXXX-XXXX-XXXX-XXXX (groupes alphanumériques)
function genKey(): string {
    $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // pas de 0/O/1/I/L
    $groups = [];
    for ($g = 0; $g < 4; $g++) {
        $s = '';
        for ($i = 0; $i < 4; $i++) $s .= $alphabet[random_int(0, strlen($alphabet) - 1)];
        $groups[] = $s;
    }
    return 'PRSRV-' . implode('-', $groups);
}

// Boucle au cas (très improbable) où collision UNIQUE
for ($attempts = 0; $attempts < 5; $attempts++) {
    $key = genKey();
    try {
        $stmt = $db->prepare(
            'INSERT INTO licenses (license_key, owner_name, issued_at, download_entitlement_until, max_machines)
             VALUES (?, ?, NOW(), ?, ?)'
        );
        $stmt->execute([$key, $owner, $until . ' 23:59:59', $maxMachines]);
        $id = $db->lastInsertId();
        echo "==== License émise ====\n";
        echo "id     : {$id}\n";
        echo "owner  : {$owner}\n";
        echo "until  : {$until}\n";
        echo "key    : {$key}\n";
        exit(0);
    } catch (\PDOException $e) {
        if (str_contains($e->getMessage(), 'Duplicate')) continue;
        throw $e;
    }
}
fwrite(STDERR, "Failed to generate unique key after retries\n"); exit(3);
