#!/usr/bin/env php
<?php

declare(strict_types=1);

use Xamma\Security\ApiKeyCipher;
use Xamma\Support\Environment;

$root = dirname(__DIR__);
require $root . '/vendor/autoload.php';
Environment::load($root . '/.env');

$apiKey = (string) ($argv[1] ?? '');
$email = strtolower(trim((string) ($argv[2] ?? '')));
$applicationKey = Environment::get('APP_KEY', '');
if (strlen($apiKey) < 24 || !filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($applicationKey) < 32) {
    fwrite(STDERR, "Usage: php bin/create-api-key <random-key-at-least-24-characters> publisher@example.com\nAPP_KEY in .env must contain at least 32 characters.\n");
    exit(1);
}

$name = 'credential_' . substr(hash('sha256', $email . "\0" . $apiKey), 0, 16);
$encrypted = ApiKeyCipher::encrypt($apiKey, $email, $applicationKey);
fwrite(STDOUT, $name . '="' . $encrypted . '"' . PHP_EOL);
