#!/usr/bin/env bash
# Deploy OMNL banking portal into Proxmox LXC via pct.
set -euo pipefail

REPO_DIR="${OMNL_BANK_ROOT:-$HOME/smom-dbis-138}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/omnl-pve-ssh.sh
source "${SCRIPT_DIR}/lib/omnl-pve-ssh.sh"

CTID="${OMNL_PCT_CTID:-5825}"
PORTAL_ROOT="${OMNL_PORTAL_ROOT:-/srv/zardasht-portal}"
PROJECT_SRC="${OMNL_PROJECT_SRC:-/home/projects/exchange}"
STAGE="/tmp/omnl-banking-portal-$(date +%Y%m%d%H%M%S).tar.gz"

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

pct_exec() {
  omnl_pve_ssh "pct exec ${CTID} -- $*"
}

pve_exec() {
  omnl_pve_ssh "$*"
}

omnl_pve_preflight

if ! omnl_pve_ensure_ct_running "$CTID"; then
  log "Skip CT ${CTID} — not available on PVE"
  exit 2
fi

if [[ "${OMNL_SKIP_BUILD:-0}" != "1" ]]; then
  log "Building OMNL stack at $REPO_DIR..."
  cd "$REPO_DIR"
  bash scripts/deployment/deploy-omnl-bank-production.sh
else
  log "Skipping build (OMNL_SKIP_BUILD=1) — using existing dist/ artifacts"
  cd "$REPO_DIR"
fi

log "Staging bundle for CT ${CTID}..."
tar -czf "$STAGE" \
  -C "$REPO_DIR" \
  config \
  frontend-dapp/dist \
  packages/integration-foundation/dist \
  packages/settlement-core/dist \
  services/token-aggregation/dist \
  services/token-aggregation/package.json \
  services/token-aggregation/package-lock.json \
  services/settlement-middleware/dist \
  services/settlement-middleware/package.json \
  services/settlement-middleware/package-lock.json \
  services/dbis-exchange/dist \
  services/dbis-exchange/package.json \
  services/dbis-exchange/package-lock.json \
  scripts/deployment/start-omnl-banking-portal.sh \
  deploy/nginx/omnl-lxc-portal.conf \
  deploy/nginx/omnl-portal-auth-current.conf.inc

if [[ -f "$REPO_DIR/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_DIR/.env"
  set +a
  if bash "$SCRIPT_DIR/generate-portal-nginx-auth-snippet.sh" "$CTID" "$REPO_DIR/deploy/nginx/omnl-portal-auth-${CTID}.conf.inc" 2>/dev/null; then
    cp "$REPO_DIR/deploy/nginx/omnl-portal-auth-${CTID}.conf.inc" "$REPO_DIR/deploy/nginx/omnl-portal-auth-current.conf.inc"
  fi
fi

log "Push to PVE host ${OMNL_PVE_SSH_TARGET}..."
omnl_pve_scp "$STAGE" "${OMNL_PVE_SSH_TARGET}:/tmp/omnl-portal.tar.gz"
rm -f "$STAGE"

log "Install into CT $CTID at $PORTAL_ROOT..."
pve_exec "pct push ${CTID} /tmp/omnl-portal.tar.gz /tmp/omnl-portal.tar.gz"
pct_exec "mkdir -p ${PORTAL_ROOT} ${PROJECT_SRC}"
pct_exec "tar -xzf /tmp/omnl-portal.tar.gz -C ${PORTAL_ROOT}"
pct_exec "ln -sfn ${PORTAL_ROOT} ${PROJECT_SRC}/omnl-live || true"
pct_exec "chmod +x ${PORTAL_ROOT}/scripts/deployment/start-omnl-banking-portal.sh"

log "Start services inside CT..."
pct_exec "bash ${PORTAL_ROOT}/scripts/deployment/start-omnl-banking-portal.sh"

log "Done — portal root: ${PORTAL_ROOT} (CT ${CTID} on ${OMNL_PVE_SSH_TARGET})"
