#!/usr/bin/env bash
# Write nginx auth snippet for portal (injects super-admin Bearer + internal header server-side).
set -euo pipefail

REPO_DIR="${OMNL_BANK_ROOT:-$HOME/smom-dbis-138}"
ENV_FILE="${OMNL_BANK_ENV:-$REPO_DIR/.env}"
CTID="${1:-5827}"
OUT="${2:-$REPO_DIR/deploy/nginx/omnl-portal-auth-${CTID}.conf.inc}"

CONFIG="$REPO_DIR/config/omnl-super-admins.v1.json"

if [[ ! -f "$ENV_FILE" ]]; then
  echo "Missing $ENV_FILE" >&2
  exit 1
fi

set -a
# shellcheck disable=SC1090
source "$ENV_FILE"
set +a

ENV_KEY="$(node -e "
const fs = require('fs');
const cfg = JSON.parse(fs.readFileSync('$CONFIG', 'utf8'));
const ct = Number('$CTID');
const admin = cfg.superAdmins.find(a => a.portalCtid === ct);
if (!admin) process.exit(2);
console.log(admin.envKey);
")"

API_KEY="${!ENV_KEY:-${OMNL_API_KEY:-}}"
INTERNAL="${OMNL_PORTAL_INTERNAL_SECRET:-}"

if [[ -z "$API_KEY" ]]; then
  echo "No API key for CT $CTID ($ENV_KEY unset)" >&2
  exit 1
fi

mkdir -p "$(dirname "$OUT")"
cat >"$OUT" <<EOF
# Auto-generated — do not commit. CT $CTID portal upstream auth.
proxy_set_header Authorization "Bearer ${API_KEY}";
proxy_set_header X-OMNL-Portal-Auth "${INTERNAL}";
EOF

chmod 600 "$OUT"
echo "Wrote $OUT"
