#!/usr/bin/env bash
# ==============================================================================
# 33-pbx-normalize-esl.sh — Normalize Remote telephony_servers ESL Routing
# Runs on pbx-admin-01 after initial deploy or Day-2 FreeSWITCH scaling (Trap #6).
# ==============================================================================
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

: "${TELEPHONY_NODE_IPS:?TELEPHONY_NODE_IPS (comma-separated) is required}"

r2a_step 1 2 "Normalizing public.telephony_servers (is_local=false, esl_host=host)"
# shellcheck disable=SC1091
source /etc/softswitch/pbx-db-credentials

IN_LIST=""
IFS=',' read -ra T_ARR <<< "$TELEPHONY_NODE_IPS"
for ip in "${T_ARR[@]}"; do
  ip="$(echo "$ip" | xargs)"
  IN_LIST+="'${ip}',"
done
IN_LIST="${IN_LIST%,}"

PGPASSWORD="$DB_PASSWORD" psql -h 127.0.0.1 -p 5000 -U "$DB_USER" -d ss_admin -v ON_ERROR_STOP=1 -c "
  UPDATE public.telephony_servers
  SET is_local = false,
      esl_host = host,
      name = CASE WHEN name = 'Local Server' THEN 'Telephony Server (' || host || ')' ELSE name END
  WHERE host IN (${IN_LIST});
"

ACTIVE_COUNT="$(PGPASSWORD="$DB_PASSWORD" psql -h 127.0.0.1 -p 5000 -U "$DB_USER" -d ss_admin -tAc "
  SELECT COUNT(*) FROM public.telephony_servers WHERE host IN (${IN_LIST}) AND is_active = true;
")"

r2a_step 2 2 "Restarting softswitch-monitoring-api & softswitch-api to refresh ESL pool"
systemctl restart softswitch-monitoring-api softswitch-api
sleep 2

r2a_ok "Normalized ${ACTIVE_COUNT} remote FreeSWITCH telephony servers for native ESL :8021."
r2a_result "{\"normalized_telephony_nodes\":${ACTIVE_COUNT}}"
