<?php
/**
 * Set (or reset) the console admin password. Run it yourself so the password
 * never enters an agent's context:
 *
 *   php api/cli/set-admin-password.php <username> <password>
 *
 * Upserts on username. The plaintext is hashed with bcrypt and never stored.
 */

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../config.php';

$username = $argv[1] ?? '';
$password = $argv[2] ?? '';

if ($username === '' || $password === '') {
    fwrite(STDERR, "usage: php api/cli/set-admin-password.php <username> <password>\n");
    exit(1);
}
if (strlen($password) < 12) {
    fwrite(STDERR, "Refusing: use at least 12 characters.\n");
    exit(1);
}

$hash = password_hash($password, PASSWORD_DEFAULT);

$existing = Db::getValue('SELECT admin_id FROM cja_admin WHERE username = ?', [$username]);
if ($existing) {
    Db::update('cja_admin', ['password_hash' => $hash], 'admin_id = ?', [$existing]);
    echo "  updated password for '{$username}'\n";
} else {
    Db::insert('cja_admin', ['username' => $username, 'password_hash' => $hash]);
    echo "  created admin '{$username}'\n";
}
