#!/usr/bin/env bash
# ==============================================================================
# 10-pg-ha-node.sh — Phase 1: PostgreSQL 17 + pgvector + Etcd + Patroni + Softdog
# Resolves Manual 19 Traps #1, #2, #3, #4, and #16 with dynamic RAM auto-tuning.
# ==============================================================================
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
r2a_require_debian13
r2a_detect_sizing

: "${NODE_HOSTNAME:?NODE_HOSTNAME is required}"
: "${NODE_IP:?NODE_IP is required}"
: "${ETCD_NAME:?ETCD_NAME is required}"
: "${ETCD_INITIAL_CLUSTER:?ETCD_INITIAL_CLUSTER is required}"
: "${PG_NODE_IPS:?PG_NODE_IPS (comma-separated) is required}"
: "${CLUSTER_SUBNET:?CLUSTER_SUBNET (e.g. 192.168.10.0/24) is required}"
: "${PG_SUPERUSER_PASS:?PG_SUPERUSER_PASS is required}"
: "${PG_REPLICATION_PASS:?PG_REPLICATION_PASS is required}"
CLUSTER_SCOPE="${PG_CLUSTER_SCOPE:-ring2all-db-cluster}"
ETCD_TOKEN="${ETCD_CLUSTER_TOKEN:-ring2all-etcd-cluster}"

r2a_step 1 6 "Configuring PGDG repository and installing PostgreSQL 17, pgvector, Etcd & Patroni"
r2a_sync_clock
install -d /usr/share/postgresql-common/pgdg
if [[ ! -f /usr/share/postgresql-common/pgdg/apt.postgresql.org.gpg ]]; then
  curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc \
    | gpg --dearmor --yes -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.gpg
fi
echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.gpg] https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" \
  > /etc/apt/sources.list.d/pgdg.list

apt-get update -y
apt-get install -y \
  postgresql-17 postgresql-client-17 postgresql-contrib-17 postgresql-17-pgvector \
  etcd-server etcd-client patroni python3-etcd python3-psycopg2

python3 -c "import patroni.dcs.etcd3; print('etcd3 module verified')" \
  || r2a_fail "python3-etcd failed to import patroni.dcs.etcd3."

r2a_step 2 6 "Masking OS standalone PostgreSQL units so only Patroni manages PostgreSQL"
if ! systemctl is-active --quiet patroni; then
  systemctl stop postgresql patroni 2>/dev/null || true
fi
systemctl disable postgresql 2>/dev/null || true
systemctl mask postgresql postgresql@17-main 2>/dev/null || true

r2a_step 3 6 "Applying Database HA firewall rules (nftables + NMS SNMPv3/Agent)"
PG_SET_NFT="$(echo "$PG_NODE_IPS" | sed 's/,/, /g')"
NMS_SRC="${NMS_SERVER_IP:-$CLUSTER_SUBNET}"
cat << EOF > /etc/nftables.conf
#!/usr/sbin/nft -f

flush ruleset

table inet filter {
    chain input {
        type filter hook input priority 0; policy drop;

        iif "lo" accept
        ct state established,related accept
        ct state invalid drop

        tcp dport 22 accept
        ip protocol icmp accept

        # Ring2All NMS SNMPv3 (161/udp) & Native Node Control API (9443/tcp)
        ip saddr ${NMS_SRC} udp dport 161 accept
        ip saddr ${NMS_SRC} tcp dport 9443 accept

        # Consensus & Replication between DB nodes
        ip saddr { ${PG_SET_NFT} } tcp dport { 5432, 8008, 2379, 2380 } accept

        # Application & Telephony HAProxy access (PostgreSQL + Patroni REST API)
        ip saddr ${CLUSTER_SUBNET} tcp dport { 5432, 8008 } accept
    }
    chain forward { type filter hook forward priority 0; policy drop; }
    chain output  { type filter hook output priority 0; policy accept; }
}
EOF
systemctl enable --now nftables
nft -f /etc/nftables.conf

r2a_step 4 6 "Configuring and starting Etcd consensus member (${ETCD_NAME})"
ETCD_ALREADY_HEALTHY=false
if systemctl is-active --quiet etcd && ETCDCTL_API=3 etcdctl --endpoints="http://${NODE_IP}:2379" endpoint health >/dev/null 2>&1; then
  ETCD_ALREADY_HEALTHY=true
  r2a_info "Etcd member ${ETCD_NAME} is already active and healthy; preserving existing WAL."
fi

if [[ "$ETCD_ALREADY_HEALTHY" == "false" ]]; then
  systemctl stop etcd 2>/dev/null || true
  rm -rf /var/lib/etcd/default/*
  cat << EOF > /etc/default/etcd
ETCD_NAME="${ETCD_NAME}"
ETCD_DATA_DIR="/var/lib/etcd/default"
ETCD_LISTEN_PEER_URLS="http://${NODE_IP}:2380"
ETCD_LISTEN_CLIENT_URLS="http://${NODE_IP}:2379,http://127.0.0.1:2379"
ETCD_INITIAL_ADVERTISE_PEER_URLS="http://${NODE_IP}:2380"
ETCD_ADVERTISE_CLIENT_URLS="http://${NODE_IP}:2379"
ETCD_INITIAL_CLUSTER="${ETCD_INITIAL_CLUSTER}"
ETCD_INITIAL_CLUSTER_STATE="new"
ETCD_INITIAL_CLUSTER_TOKEN="${ETCD_TOKEN}"
EOF
  systemctl enable etcd
  systemctl start --no-block etcd
fi

r2a_step 5 6 "Enabling Linux softdog kernel watchdog and preparing PostgreSQL 17 data directories"
modprobe softdog || r2a_warn "softdog module unavailable in this kernel; Patroni watchdog will run in best-effort mode."
echo "softdog" > /etc/modules-load.d/softdog.conf
echo 'KERNEL=="watchdog", MODE="0660", GROUP="postgres"' > /etc/udev/rules.d/60-watchdog.rules
udevadm control --reload-rules && udevadm trigger || true

if ! systemctl is-active --quiet patroni; then
  rm -rf /var/lib/postgresql/17/main/*
fi
mkdir -p /var/lib/postgresql/17/main /var/lib/postgresql/17/archive
chown -R postgres:postgres /var/lib/postgresql/17
chmod 700 /var/lib/postgresql/17/main

r2a_step 6 6 "Generating auto-tuned /etc/patroni/config.yml and WAL archive retention cron"
mkdir -p /etc/patroni
ETCD_YAML_HOSTS=""
IFS=',' read -ra PG_ARR <<< "$PG_NODE_IPS"
for ip in "${PG_ARR[@]}"; do
  ip="$(echo "$ip" | xargs)"
  ETCD_YAML_HOSTS+="    - ${ip}:2379"$'\n'
done

cat << EOF > /etc/patroni/config.yml
scope: ${CLUSTER_SCOPE}
namespace: /db/
name: ${NODE_HOSTNAME}

restapi:
  listen: ${NODE_IP}:8008
  connect_address: ${NODE_IP}:8008

etcd3:
  hosts:
${ETCD_YAML_HOSTS}
bootstrap:
  dcs:
    ttl: 30
    loop_wait: 10
    retry_timeout: 10
    maximum_lag_on_failover: 1048576
    postgresql:
      use_pg_rewind: true
      use_slots: true
      pg_hba:
        - local all all trust
        - host replication replicator ${CLUSTER_SUBNET} scram-sha-256
        - host all all 127.0.0.1/32 scram-sha-256
        - host all all ::1/128 scram-sha-256
        - host all all ${CLUSTER_SUBNET} scram-sha-256
      parameters:
        wal_level: replica
        hot_standby: "on"
        wal_keep_size: 256MB
        max_wal_senders: 10
        max_replication_slots: 10
        max_connections: ${PG_MAX_CONNECTIONS}
        shared_buffers: ${PG_SHARED_BUFFERS_MB}MB
        effective_cache_size: ${PG_EFFECTIVE_CACHE_MB}MB
        work_mem: ${PG_WORK_MEM_MB}MB
        tcp_keepalives_idle: 60
        idle_in_transaction_session_timeout: 60000
        wal_log_hints: "on"
        wal_compression: "on"
        password_encryption: scram-sha-256
        archive_mode: "on"
        archive_command: "test ! -f /var/lib/postgresql/17/archive/%f && cp %p /var/lib/postgresql/17/archive/%f"

  initdb:
    - encoding: UTF8
    - data-checksums

postgresql:
  listen: ${NODE_IP}:5432
  connect_address: ${NODE_IP}:5432
  data_dir: /var/lib/postgresql/17/main
  bin_dir: /usr/lib/postgresql/17/bin
  pgpass: /tmp/pgpass
  authentication:
    replication:
      username: replicator
      password: "${PG_REPLICATION_PASS}"
    superuser:
      username: postgres
      password: "${PG_SUPERUSER_PASS}"
  parameters:
    unix_socket_directories: '/var/run/postgresql'
  pg_hba:
    - local all all trust
    - host replication replicator ${CLUSTER_SUBNET} scram-sha-256
    - host all all 127.0.0.1/32 scram-sha-256
    - host all all ::1/128 scram-sha-256
    - host all all ${CLUSTER_SUBNET} scram-sha-256

watchdog:
  mode: automatic
  device: /dev/watchdog
  safety_margin: 5

tags:
  nofailover: false
  noloadbalance: false
  clonefrom: false
  nosync: false
EOF

chown postgres:postgres /etc/patroni/config.yml
chmod 600 /etc/patroni/config.yml

# Daily WAL archive retention cleanup (Manual 19 Trap #16)
cat << 'EOF' > /etc/cron.daily/pg-archive-cleanup
#!/bin/sh
find /var/lib/postgresql/17/archive -type f -mtime +2 -delete 2>/dev/null || true
EOF
chmod 755 /etc/cron.daily/pg-archive-cleanup

r2a_ok "PostgreSQL 17 HA node prepared (${NODE_HOSTNAME}, shared_buffers=${PG_SHARED_BUFFERS_MB}MB, max_connections=${PG_MAX_CONNECTIONS})."
r2a_result "{\"node\":\"${NODE_HOSTNAME}\",\"ip\":\"${NODE_IP}\",\"shared_buffers_mb\":${PG_SHARED_BUFFERS_MB},\"max_connections\":${PG_MAX_CONNECTIONS}}"
