#!/usr/bin/env bash
# ==============================================================================
# 30-client-haproxy.sh — Local HAProxy PostgreSQL HA Router (:5000 R/W, :5001 R/O)
# Implements Manual 19 Trap #10 (option tcpka, 12h timeouts, dynamic maxconn).
# ==============================================================================
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

: "${PG_NODE_ENTRIES:?PG_NODE_ENTRIES (comma-separated name:ip pairs, e.g. pg-node-01:192.168.10.30,...) is required}"

r2a_step 1 3 "Installing HAProxy and PostgreSQL client utilities"
apt-get update -y
apt-get install -y haproxy postgresql-client

r2a_step 2 3 "Rendering /etc/haproxy/haproxy.cfg (maxconn=${HAPROXY_MAXCONN}, tcpka, 12h timeout)"
PRIMARY_LINES=""
REPLICA_LINES=""
IFS=',' read -ra ENTRIES <<< "$PG_NODE_ENTRIES"
for entry in "${ENTRIES[@]}"; do
  name="${entry%%:*}"
  ip="${entry##*:}"
  name="$(echo "$name" | xargs)"
  ip="$(echo "$ip" | xargs)"
  PRIMARY_LINES+="    server ${name} ${ip}:5432 maxconn ${HAPROXY_MAXCONN} maxqueue 50 check port 8008"$'\n'
  REPLICA_LINES+="    server ${name} ${ip}:5432 check port 8008"$'\n'
done

cat << EOF > /etc/haproxy/haproxy.cfg
global
    log /dev/log local0
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin
    stats timeout 30s
    user haproxy
    group haproxy
    daemon

defaults
    log global
    mode tcp
    option tcplog
    option tcpka
    timeout connect 5000ms
    timeout client 12h
    timeout server 12h

frontend pg_write
    bind 127.0.0.1:5000
    default_backend pg_primary

backend pg_primary
    mode tcp
    option httpchk GET /primary
    http-check expect status 200
    default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions
${PRIMARY_LINES}
frontend pg_read
    bind 127.0.0.1:5001
    default_backend pg_replicas

backend pg_replicas
    mode tcp
    balance roundrobin
    option httpchk GET /replica
    http-check expect status 200
    default-server inter 3s fall 3 rise 2
${REPLICA_LINES}
EOF

r2a_step 3 3 "Validating and starting HAProxy"
haproxy -c -f /etc/haproxy/haproxy.cfg
systemctl enable --now haproxy
systemctl restart haproxy

r2a_wait_for_tcp "127.0.0.1" 5000 30 || r2a_fail "HAProxy write port 127.0.0.1:5000 did not come online."
r2a_ok "Local HAProxy active on 127.0.0.1:5000 (write) and 127.0.0.1:5001 (read)."
r2a_result "{\"write_port\":5000,\"read_port\":5001,\"maxconn\":${HAPROXY_MAXCONN}}"
