#!/usr/bin/env php
<?php
/**
 * One-time Ed25519 keypair generation for release signing.
 *
 * Usage: php scripts/generate-keypair.php
 *
 * Saves the private key to ~/.mv-release-key (base64, mode 0600).
 * Prints the public key constant to paste into SelfUpdateService.php.
 */

if (!function_exists('sodium_crypto_sign_keypair')) {
    fwrite(STDERR, "ERROR: sodium extension is required (bundled in PHP 7.2+).\n");
    exit(1);
}

$keyFile = $_SERVER['HOME'] . '/.mv-release-key';

if (file_exists($keyFile)) {
    fwrite(STDERR, "WARNING: $keyFile already exists.\n");
    fwrite(STDERR, "Delete it first if you want to generate a new keypair.\n");
    fwrite(STDERR, "\n");

    // Show existing public key
    $secretKeyBase64 = trim(file_get_contents($keyFile));
    $secretKey = base64_decode($secretKeyBase64);
    $publicKey = sodium_crypto_sign_publickey_from_secretkey($secretKey);
    $publicKeyBase64 = base64_encode($publicKey);

    echo "Existing public key:\n\n";
    echo "    private const PUBLIC_KEY = '$publicKeyBase64';\n\n";
    exit(0);
}

// Generate keypair
$keypair = sodium_crypto_sign_keypair();
$secretKey = sodium_crypto_sign_secretkey($keypair);
$publicKey = sodium_crypto_sign_publickey($keypair);

$secretKeyBase64 = base64_encode($secretKey);
$publicKeyBase64 = base64_encode($publicKey);

// Save private key
file_put_contents($keyFile, $secretKeyBase64 . "\n");
chmod($keyFile, 0600);

echo "Ed25519 keypair generated.\n\n";
echo "Private key saved to: $keyFile\n";
echo "  (mode 0600 — keep this secret!)\n\n";
echo "Public key (paste into lib/Service/SelfUpdateService.php):\n\n";
echo "    private const PUBLIC_KEY = '$publicKeyBase64';\n\n";
echo "Store the private key in:\n";
echo "  1. Gitea repo secret 'MV_RELEASE_KEY' (primary)\n";
echo "  2. Your password manager (backup)\n";
echo "\nBase64 private key for copy-paste:\n";
echo "$secretKeyBase64\n";
