#!/usr/bin/env bash
# ==============================================================================
# 13-pg-init-databases.sh — Initialize All Ring2All Databases (--all-db) on Leader
# Runs strictly on the active Patroni Leader and validates isolated credential files.
# ==============================================================================
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/common.sh
source "${SCRIPT_DIR}/lib/common.sh"

r2a_load_env
r2a_require_root

: "${NODE_IP:?NODE_IP is required}"
APT_REPO_BASE="${APT_REPO_BASE:-https://repo.softswitchone.com/apt}"

r2a_step 1 3 "Verifying this node (${NODE_IP}) holds the active Patroni Primary lock"
if ! r2a_wait_for_http_200 "http://${NODE_IP}:8008/primary" 15; then
  r2a_fail "Refusing to run --all-db: ${NODE_IP} is NOT the active Patroni Primary."
fi

r2a_step 2 3 "Initializing all Ring2All platform databases via install-softswitch.sh --all-db -y"
if [[ -f /etc/softswitch/pbx-db-credentials && -f /etc/softswitch/sbc-db-credentials && -f /etc/softswitch/bss-db-credentials ]]; then
  r2a_info "Platform DB credential files already exist; verifying schemas..."
else
  wget -qO- "${APT_REPO_BASE}/install-softswitch.sh" | bash -s -- --all-db -y
fi

# Ensure ss_billing exists explicitly (Manual 19 Step 5.1 safety check)
if ! sudo -u postgres psql -tAc "SELECT 1 FROM pg_database WHERE datname='ss_billing'" | grep -q 1; then
  r2a_info "Installing softswitch-bss-db to provision ss_billing..."
  r2a_setup_ring2all_repo
  apt-get install -y softswitch-bss-db
fi

r2a_step 3 3 "Verifying replicated databases and isolated credential files"
DB_COUNT="$(sudo -u postgres psql -tAc "SELECT COUNT(*) FROM pg_database WHERE datname IN ('ss_admin','ss_telephony','ss_cdr','sbc_admin','kamailio','ss_billing')")"
if (( DB_COUNT < 6 )); then
  r2a_fail "Expected core platform databases missing (found ${DB_COUNT}/6)."
fi

CRED_FILES=()
for cf in /etc/softswitch/*-db-credentials; do
  [[ -f "$cf" ]] && CRED_FILES+=("$(basename "$cf")")
done
CRED_JSON="$(printf '"%s",' "${CRED_FILES[@]}")"
CRED_JSON="[${CRED_JSON%,}]"

r2a_ok "All platform databases initialized and ${#CRED_FILES[@]} isolated credential files ready."
r2a_result "{\"core_db_count\":${DB_COUNT},\"credential_files\":${CRED_JSON}}"
