#!/usr/bin/env bash
# Push production Fineract/API env keys from dev .env into an LXC portal root.
set -euo pipefail

CTID="${1:?CTID required}"
REPO_DIR="${OMNL_BANK_ROOT:-$HOME/smom-dbis-138}"
ENV_FILE="${OMNL_BANK_ENV:-$REPO_DIR/.env}"
PORTAL_ROOT="${OMNL_PORTAL_ROOT:-/srv/zardasht-portal}"
CONFIG="$REPO_DIR/config/omnl-super-admins.v1.json"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/omnl-pve-ssh.sh
source "${SCRIPT_DIR}/lib/omnl-pve-ssh.sh"

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

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

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

FRAG="$(mktemp)"
grep -E '^(OMNL_FINERACT_|OMNL_PUBLIC_MONEY_SUPPLY=|OMNL_REQUIRE_API_KEY=|OFFICE24_OPENING_M1_USD=|OMNL_PORTAL_INTERNAL_SECRET=|OMNL_CUSTOMER_SECURITY_PRODUCTION=|JWT_SECRET=)' "$ENV_FILE" >"$FRAG" || true

ADMIN_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(0);
console.log(admin.envKey);
" 2>/dev/null || true)"

if [[ -n "$ADMIN_ENV_KEY" ]]; then
  ADMIN_VAL="${!ADMIN_ENV_KEY:-}"
  if [[ -n "$ADMIN_VAL" ]]; then
    echo "OMNL_API_KEY=${ADMIN_VAL}" >>"$FRAG"
    log "Mapped CT $CTID → $ADMIN_ENV_KEY as OMNL_API_KEY"
  fi
elif [[ -n "${OMNL_API_KEY:-}" ]]; then
  echo "OMNL_API_KEY=${OMNL_API_KEY}" >>"$FRAG"
fi

if [[ ! -s "$FRAG" ]]; then
  log "No Fineract/API keys found in $ENV_FILE — skip CT $CTID"
  rm -f "$FRAG"
  exit 0
fi

log "Pushing portal env keys to CT $CTID..."
omnl_pve_scp "$FRAG" "${OMNL_PVE_SSH_TARGET}:/tmp/omnl-portal-env.frag"
rm -f "$FRAG"

if [[ -n "$ADMIN_ENV_KEY" ]] && [[ -n "${!ADMIN_ENV_KEY:-}" ]]; then
  bash "$SCRIPT_DIR/generate-portal-nginx-auth-snippet.sh" "$CTID" "$REPO_DIR/deploy/nginx/omnl-portal-auth-${CTID}.conf.inc"
  omnl_pve_scp "$REPO_DIR/deploy/nginx/omnl-portal-auth-${CTID}.conf.inc" "${OMNL_PVE_SSH_TARGET}:/tmp/omnl-portal-auth.conf.inc"
  omnl_pve_ssh "pct push ${CTID} /tmp/omnl-portal-auth.conf.inc ${PORTAL_ROOT}/deploy/nginx/omnl-portal-auth-current.conf.inc"
  omnl_pve_ssh "pct exec ${CTID} -- chmod 600 ${PORTAL_ROOT}/deploy/nginx/omnl-portal-auth-current.conf.inc"
fi

omnl_pve_ssh "pct push ${CTID} /tmp/omnl-portal-env.frag /tmp/omnl-portal-env.frag"

omnl_pve_ssh "pct exec ${CTID} -- bash -s" <<EOF
set -euo pipefail
touch ${PORTAL_ROOT}/.env
if [[ -x ${PORTAL_ROOT}/scripts/deployment/merge-env-fragment.sh ]]; then
  bash ${PORTAL_ROOT}/scripts/deployment/merge-env-fragment.sh ${PORTAL_ROOT}/.env /tmp/omnl-portal-env.frag
else
  while IFS= read -r line; do
    key="\${line%%=*}"
    grep -v "^\${key}=" ${PORTAL_ROOT}/.env > ${PORTAL_ROOT}/.env.new || true
    mv ${PORTAL_ROOT}/.env.new ${PORTAL_ROOT}/.env
    echo "\$line" >> ${PORTAL_ROOT}/.env
  done < /tmp/omnl-portal-env.frag
  chmod 600 ${PORTAL_ROOT}/.env
fi
rm -f /tmp/omnl-portal-env.frag
EOF

log "Env synced on CT $CTID"
