#!/usr/bin/env bash
# pg_rewind 가 postgres 데이터베이스에 접속할 수 있도록 각 노드 pg_hba.conf 에 규칙을 추가하고 reload 한다.
# --dbname 을 postgres 가 아닌 값으로 만든 노드는 pg_autoctl 이 그 DB 에 대한 규칙만 만들기 때문에
# 옛 primary 를 되살릴 때 pg_rewind 가 거부되고 pg_basebackup 으로 전체 복사를 한다(2.2 에서 측정).
# 사용: ./scripts/allow-rewind.sh node1 node2 [node3]
set -euo pipefail
cd "$(dirname "$0")/.."
DC="docker compose"; $DC version >/dev/null 2>&1 || DC=docker-compose
rule='hostssl "postgres" "pgautofailover_replicator" 172.28.0.0/24 trust # added for pg_rewind (lab)'
for n in "$@"; do
  $DC exec -T "$n" bash -c "grep -qF 'added for pg_rewind' \$PGDATA/pg_hba.conf || echo '$rule' >> \$PGDATA/pg_hba.conf; psql -d postgres -Atqc 'select pg_reload_conf()' >/dev/null"
  echo "$n: rule ensured"
done
