#!/usr/bin/env bash
# Sync OMNL banking portal to banking LXCs via Proxmox pct.
set -euo pipefail

REPO_DIR="${OMNL_BANK_ROOT:-$HOME/smom-dbis-138}"
DEPLOY_SCRIPT="${REPO_DIR}/scripts/deployment/deploy-omnl-banking-portal-pct.sh"
LXC_CONFIG="${OMNL_BANKING_LXC_CONFIG:-$REPO_DIR/config/omnl-banking-portal-lxcs.v1.json}"
APPLY=false

if [[ "${1:-}" == "--apply" ]]; then
  APPLY=true
fi

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

if [[ ! -f "$DEPLOY_SCRIPT" ]]; then
  echo "Missing deploy script: $DEPLOY_SCRIPT" >&2
  exit 1
fi

read_ctids() {
  if [[ -n "${OMNL_BANKING_LXC_CTIDS:-}" ]]; then
    # shellcheck disable=SC2206
    CTIDS=(${OMNL_BANKING_LXC_CTIDS})
    return
  fi
  if command -v node >/dev/null 2>&1 && [[ -f "$LXC_CONFIG" ]]; then
    mapfile -t CTIDS < <(node -e "
      const c=require(process.argv[1]);
      for (const x of c.containers||[]) console.log(x.ctid);
    " "$LXC_CONFIG")
    return
  fi
  CTIDS=(5825 5826 5827 5828)
}

read_ctids

# shellcheck source=lib/omnl-pve-ssh.sh
source "${REPO_DIR}/scripts/deployment/lib/omnl-pve-ssh.sh"
omnl_pve_preflight

log "OMNL banking LXC sync — CTIDs: ${CTIDS[*]}"
log "Mode: $(if $APPLY; then echo APPLY; else echo DRY-RUN; fi)"
log "Repo: $REPO_DIR"
log "Config: $LXC_CONFIG"
log "PVE: ${OMNL_PVE_SSH_TARGET} (sudo prefix: ${OMNL_PVE_SSH_PREFIX[*]:-none})"

if $APPLY; then
  log "Building stack once on dev..."
  cd "$REPO_DIR"
  bash scripts/deployment/deploy-omnl-bank-production.sh
fi

synced=0
skipped=0
for CTID in "${CTIDS[@]}"; do
  if $APPLY; then
    log "Deploying CT $CTID..."
    set +e
    OMNL_SKIP_BUILD=1 OMNL_PCT_CTID="$CTID" OMNL_BANK_ROOT="$REPO_DIR" bash "$DEPLOY_SCRIPT"
    rc=$?
    set -e
    if [[ $rc -eq 0 ]]; then
      synced=$((synced + 1))
    elif [[ $rc -eq 2 ]]; then
      skipped=$((skipped + 1))
    else
      log "WARN: deploy failed for CT $CTID (exit $rc, continuing)"
    fi
  else
    log "Would deploy CT $CTID → /srv/ali-portal (pct exec on ${OMNL_PVE_SSH_TARGET})"
  fi
done

if $APPLY; then
  log "Synced ${synced}/${#CTIDS[@]} banking LXCs (${skipped} skipped)."
else
  log "Dry-run complete. Re-run with --apply to deploy."
fi
