#!/usr/bin/env bash
# Menyiapkan publisher dan subscriber untuk demo logical replication.
# Publisher (kantor pusat) di port 54351 dengan wal_level=logical,
# subscriber (cabang) di port 54352 sebagai server normal yang bisa ditulis.
# Skrip berikutnya (langganan.sh) melanjutkan pasangan server ini.
set -eu

PGBIN=/home/z/my-project/tools/dl/pgdeb/usr/lib/postgresql/17/bin
BASE=/home/z/my-project/tmp/rp_logical
PUB=$BASE/pgdata_pusat    # publisher, port 54351
SUB=$BASE/pgdata_cabang   # subscriber, port 54352
SOCK=$BASE/sock

# Buang sisa percobaan sebelumnya bila ada.
"$PGBIN/pg_ctl" -D "$PUB" -m immediate stop >/dev/null 2>&1 || true
"$PGBIN/pg_ctl" -D "$SUB" -m immediate stop >/dev/null 2>&1 || true
rm -rf "$BASE"
mkdir -p "$SOCK"

# Polling: tunggu sampai sebuah query mengembalikan nilai yang diharapkan.
tunggu() {  # port database sql nilai_yang_diharapkan
  local port="$1" db="$2" sql="$3" harapan="$4" i hasil
  for i in $(seq 1 80); do
    hasil=$(psql -X -q -t -A -h 127.0.0.1 -p "$port" -U postgres -d "$db" \
            -c "$sql" 2>/dev/null) || true
    if [ "$hasil" = "$harapan" ]; then return 0; fi
    sleep 0.2
  done
  echo "TIMEOUT: menunggu '$sql' menjadi $harapan (port $port)" >&2
  return 1
}

echo "== Langkah 1: initdb dua cluster =="
"$PGBIN/initdb" -D "$PUB" --no-locale -E UTF8 -U postgres >/dev/null 2>&1
"$PGBIN/initdb" -D "$SUB" --no-locale -E UTF8 -U postgres >/dev/null 2>&1

echo "== Langkah 2: jalankan publisher dengan wal_level=logical =="
"$PGBIN/pg_ctl" -D "$PUB" \
  -o "-p 54351 -k $SOCK -c listen_addresses=127.0.0.1 -c wal_level=logical" \
  -l "$BASE/publisher.log" start >/dev/null 2>&1
tunggu 54351 postgres "SHOW wal_level;" "logical"

echo "== Langkah 3: jalankan subscriber (server normal) =="
"$PGBIN/pg_ctl" -D "$SUB" \
  -o "-p 54352 -k $SOCK -c listen_addresses=127.0.0.1" \
  -l "$BASE/subscriber.log" start >/dev/null 2>&1
tunggu 54352 postgres "SELECT 1;" "1"

echo "== Langkah 4: database dan tabel di kedua sisi =="
psql -X -h 127.0.0.1 -p 54351 -U postgres -d postgres \
  -c "CREATE DATABASE pusat;"
psql -X -h 127.0.0.1 -p 54352 -U postgres -d postgres \
  -c "CREATE DATABASE cabang;"
psql -X -h 127.0.0.1 -p 54351 -U postgres -d pusat \
  -c "CREATE TABLE produk (id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, nama text NOT NULL, harga numeric);" \
  -c "INSERT INTO produk (nama, harga) VALUES ('Kopi Tubruk', 15000), ('Teh Celup', 8000), ('Gula Pasir', 12000);"
echo "tabel di subscriber sengaja belum dibuat"

echo "== Langkah 5: publikasikan tabel produk =="
psql -X -h 127.0.0.1 -p 54351 -U postgres -d pusat \
  -c "CREATE PUBLICATION pub_produk FOR TABLE produk;"
psql -X -h 127.0.0.1 -p 54351 -U postgres -d pusat \
  -c "SELECT pubname, puballtables FROM pg_publication;" \
  -c "SELECT pubname, schemaname, tablename FROM pg_publication_tables ORDER BY tablename;"
