#!/usr/bin/env bash
# ==============================================================================
# Ring2All Horizontal Cluster Automation — Shared Common Library
# Debian 13 (Trixie) · Versioned Repository Script Contract
# ==============================================================================
set -euo pipefail

export DEBIAN_FRONTEND=noninteractive

R2A_ENV_FILE="${R2A_ENV_FILE:-}"
R2A_CLEANUP_ENV="${R2A_CLEANUP_ENV:-true}"

r2a_cleanup() {
  if [[ "$R2A_CLEANUP_ENV" == "true" && -n "$R2A_ENV_FILE" && -f "$R2A_ENV_FILE" ]]; then
    shred -u "$R2A_ENV_FILE" 2>/dev/null || rm -f "$R2A_ENV_FILE"
  fi
}
trap r2a_cleanup EXIT INT TERM

r2a_step() {
  local idx="$1"
  local total="$2"
  shift 2
  echo "@@R2A_STEP|${idx}|${total}|$*"
}

r2a_info() {
  echo "[INFO] $*"
}

r2a_ok() {
  echo "[OK] $*"
}

r2a_warn() {
  echo "[WARN] $*"
}

r2a_fail() {
  echo "[ERROR] $*" >&2
  exit 1
}

r2a_metric() {
  local key="$1"
  local val="$2"
  echo "@@R2A_METRIC|${key}|${val}"
}

r2a_result() {
  local json="$1"
  echo "@@R2A_RESULT|${json}"
}

r2a_load_env() {
  if [[ -n "$R2A_ENV_FILE" ]]; then
    if [[ ! -f "$R2A_ENV_FILE" ]]; then
      r2a_fail "Environment contract file not found: $R2A_ENV_FILE"
    fi
    chmod 600 "$R2A_ENV_FILE" 2>/dev/null || true
    # shellcheck disable=SC1090
    source "$R2A_ENV_FILE"
  fi
}

r2a_require_root() {
  if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
    r2a_fail "Cluster scripts must execute as root."
  fi
}

r2a_require_debian13() {
  if [[ ! -f /etc/os-release ]]; then
    r2a_fail "Cannot detect OS (/etc/os-release missing). Debian 13 (trixie) is required."
  fi
  # shellcheck disable=SC1091
  source /etc/os-release
  local ver="${VERSION_ID:-}"
  local codename="${VERSION_CODENAME:-}"
  if [[ "${ID:-}" != "debian" || ( "$ver" != "13" && "$codename" != "trixie" ) ]]; then
    r2a_fail "Unsupported OS detected: ID=${ID:-unknown} VERSION_ID=${ver:-unknown} CODENAME=${codename:-unknown}. Debian 13 (trixie) is strictly required."
  fi
}

# Synchronize system UTC clock before APT/PGDG OpenPGP signature verification (sqv).
# Never trusts systemd's cached NTPSynchronized=yes blindly (cloned/resumed VMs often
# report NTPSynchronized=yes while their clock is days behind UTC). Always validates
# local UTC against authoritative HTTPS Date header (with -k for skewed TLS certs).
r2a_sync_clock() {
  timedatectl set-timezone UTC 2>/dev/null || ln -sf /usr/share/zoneinfo/UTC /etc/localtime

  local probe_url="${APT_REPO_BASE:-https://repo.softswitchone.com/apt}/setup_repo"
  local remote_date=""
  if command -v curl >/dev/null 2>&1; then
    remote_date="$(curl -kfsSI --max-time 5 "$probe_url" 2>/dev/null | awk -F': ' 'tolower($1)=="date"{gsub(/\r/,"",$2); print $2; exit}' || true)"
  fi
  if [[ -z "$remote_date" ]] && command -v python3 >/dev/null 2>&1; then
    remote_date="$(python3 -c "import ssl,urllib.request; ctx=ssl._create_unverified_context(); r=urllib.request.urlopen('${probe_url}', timeout=5, context=ctx); print(r.headers.get('Date',''))" 2>/dev/null || true)"
  fi
  if [[ -z "$remote_date" ]] && command -v wget >/dev/null 2>&1; then
    remote_date="$(wget --no-check-certificate -qS --spider --timeout=5 "$probe_url" 2>&1 | awk -F': ' '/^[[:space:]]*[Dd]ate:/{gsub(/\r/,"",$2); print $2; exit}' || true)"
  fi

  if [[ -n "$remote_date" ]]; then
    local local_epoch remote_epoch diff
    local_epoch="$(date -u +%s 2>/dev/null || echo 0)"
    remote_epoch="$(date -u -d "$remote_date" +%s 2>/dev/null || echo 0)"
    if (( remote_epoch > 1700000000 )); then
      diff=$(( remote_epoch - local_epoch ))
      (( diff < 0 )) && diff=$(( -diff ))
      if (( diff > 20 )); then
        r2a_warn "Detected VM clock skew (${diff}s vs UTC). Forcing system clock to ${remote_date}..."
        timedatectl set-ntp false 2>/dev/null || true
        date -u -s "$remote_date" >/dev/null 2>&1 || true
        hwclock --systohc --utc 2>/dev/null || true
        r2a_ok "System UTC clock synchronized ($(date -u '+%Y-%m-%d %H:%M:%S UTC'))."
      fi
    fi
  fi

  timedatectl set-ntp true 2>/dev/null || true
  systemctl enable --now systemd-timesyncd 2>/dev/null || true
}

# Compute dynamic sizing parameters based on detected RAM/CPU and SIZING_PROFILE
r2a_detect_sizing() {
  local profile="${SIZING_PROFILE:-production}"
  CPU_CORES="$(nproc 2>/dev/null || echo 2)"
  MEM_TOTAL_MB="$(awk '/MemTotal:/ {printf "%d", $2/1024}' /proc/meminfo 2>/dev/null || echo 4096)"
  DISK_FREE_GB="$(df -BG --output=avail / 2>/dev/null | tail -n 1 | tr -dc '0-9' || echo 30)"

  # PostgreSQL 17 dynamic memory tuning (capped conservatively for co-resident Patroni/Etcd)
  PG_SHARED_BUFFERS_MB=$(( MEM_TOTAL_MB / 4 ))
  if (( PG_SHARED_BUFFERS_MB < 256 )); then PG_SHARED_BUFFERS_MB=256; fi
  if (( PG_SHARED_BUFFERS_MB > 16384 )); then PG_SHARED_BUFFERS_MB=16384; fi

  PG_EFFECTIVE_CACHE_MB=$(( (MEM_TOTAL_MB * 65) / 100 ))
  if (( PG_EFFECTIVE_CACHE_MB < 512 )); then PG_EFFECTIVE_CACHE_MB=512; fi

  case "$profile" in
    lab)
      PG_MAX_CONNECTIONS="${PG_MAX_CONNECTIONS:-400}"
      HAPROXY_MAXCONN="${HAPROXY_MAXCONN:-150}"
      PG_WORK_MEM_MB=8
      ;;
    carrier)
      PG_MAX_CONNECTIONS="${PG_MAX_CONNECTIONS:-1200}"
      HAPROXY_MAXCONN="${HAPROXY_MAXCONN:-500}"
      PG_WORK_MEM_MB=32
      ;;
    *)
      PG_MAX_CONNECTIONS="${PG_MAX_CONNECTIONS:-800}"
      HAPROXY_MAXCONN="${HAPROXY_MAXCONN:-250}"
      PG_WORK_MEM_MB=16
      ;;
  esac

  export CPU_CORES MEM_TOTAL_MB DISK_FREE_GB PG_SHARED_BUFFERS_MB PG_EFFECTIVE_CACHE_MB PG_WORK_MEM_MB PG_MAX_CONNECTIONS HAPROXY_MAXCONN
}

# Idempotent KEY=VALUE updater for .env files
r2a_set_env_kv() {
  local file="$1"
  local key="$2"
  local value="$3"
  touch "$file"
  if grep -q "^${key}=" "$file" 2>/dev/null; then
    local escaped
    escaped="$(printf '%s' "$value" | sed -e 's/[\/&|]/\\&/g')"
    sed -i "s|^${key}=.*|${key}=${escaped}|" "$file"
  else
    printf '%s=%s\n' "$key" "$value" >> "$file"
  fi
}

r2a_wait_for_http_200() {
  local url="$1"
  local max_wait="${2:-120}"
  local elapsed=0
  while (( elapsed < max_wait )); do
    local code
    code="$(curl -sk -o /dev/null -w '%{http_code}' --max-time 3 "$url" 2>/dev/null || echo '000')"
    if [[ "$code" == "200" ]]; then
      return 0
    fi
    sleep 2
    elapsed=$((elapsed + 2))
  done
  return 1
}

r2a_wait_for_tcp() {
  local host="$1"
  local port="$2"
  local max_wait="${3:-60}"
  local elapsed=0
  while (( elapsed < max_wait )); do
    if timeout 2 bash -c "echo > /dev/tcp/${host}/${port}" 2>/dev/null; then
      return 0
    fi
    sleep 2
    elapsed=$((elapsed + 2))
  done
  return 1
}

r2a_setup_ring2all_repo() {
  local repo_url="${APT_REPO_BASE:-https://repo.softswitchone.com/apt}"
  if [[ ! -f /etc/apt/sources.list.d/ring2all.list ]]; then
    r2a_info "Configuring Ring2All official APT repository (${repo_url})..."
    curl -fsSL "${repo_url}/setup_repo" | bash
  fi
  apt-get update -y
}

# Safely ensure the shared r2a-media group (GID 2000) exists (Manual 19 Trap #14)
r2a_ensure_media_group() {
  local gid="${MEDIA_GID:-2000}"
  local grp="${MEDIA_GROUP:-r2a-media}"
  if ! getent group "$grp" >/dev/null 2>&1; then
    if getent group "$gid" >/dev/null 2>&1; then
      r2a_warn "GID ${gid} already exists; reusing existing group for media sharing."
    else
      groupadd -g "$gid" "$grp"
    fi
  fi
}
