#!/usr/bin/env bash
# Generate four super-admin API keys + portal internal secret in .env (idempotent).
set -euo pipefail

REPO_DIR="${OMNL_BANK_ROOT:-$HOME/smom-dbis-138}"
ENV_FILE="${OMNL_BANK_ENV:-$REPO_DIR/.env}"
CONFIG="$REPO_DIR/config/omnl-super-admins.v1.json"

log() { echo "[$(date -Iseconds)] $*"; }

gen_key() {
  if command -v openssl >/dev/null 2>&1; then
    openssl rand -hex 32
  else
    node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
  fi
}

ensure_kv() {
  local key="$1"
  local val="$2"
  if grep -q "^${key}=" "$ENV_FILE" 2>/dev/null; then
    log "  $key already set — skip"
  else
    echo "${key}=${val}" >>"$ENV_FILE"
    log "  $key generated"
  fi
}

if [[ ! -f "$ENV_FILE" ]]; then
  touch "$ENV_FILE"
  chmod 600 "$ENV_FILE"
fi

log "Seeding OMNL super-admin keys into $ENV_FILE"

node -e "
const fs = require('fs');
const cfg = JSON.parse(fs.readFileSync('$CONFIG', 'utf8'));
for (const a of cfg.superAdmins) console.log(a.envKey);
" | while read -r env_key; do
  ensure_kv "$env_key" "$(gen_key)"
done

ensure_kv "OMNL_PORTAL_INTERNAL_SECRET" "$(gen_key)"
ensure_kv "OMNL_CUSTOMER_SECURITY_PRODUCTION" "1"
ensure_kv "OMNL_REQUIRE_API_KEY" "1"

if ! grep -q '^JWT_SECRET=' "$ENV_FILE" 2>/dev/null; then
  ensure_kv "JWT_SECRET" "$(gen_key)"
fi

log "Super-admin key env vars ready. Map each LXC CTID to its portal key via push-portal-env-to-lxc.sh"
