#!/bin/bash

port_primary=5433
port_standby=5434
port_subscriber=5435

echo '=========='
echo '=Clean up='
echo '=========='

pg_ctl stop -D ./primarydb
pg_ctl stop -D ./standbydb
pg_ctl stop -D ./subdb

rm -rf primarydb
rm -rf standbydb
rm -rf subdb

echo '======================='
echo '=Set up primary server='
echo '======================='

initdb -D ./primarydb

cat << EOF >> ./primarydb/postgresql.conf
wal_level = logical
port = $port_primary
#standby_slot_names = 'standby_1'
max_wal_senders=500
max_worker_processes=1000
max_replication_slots=500
log_replication_commands = 'on'
EOF

cat << EOF >> ./primarydb/pg_hba.conf
host all,replication all 0.0.0.0/0 trust
EOF

pg_ctl -D ./primarydb/ -w -l primarydb.log start
psql -p $port_primary -d postgres -c "SELECT pg_create_physical_replication_slot('standby_1');"
psql -p $port_primary -d postgres -c "CREATE ROLE replication WITH REPLICATION PASSWORD 'password' LOGIN;"
pg_ctl -D ./primarydb/ -w -l primarydb.log restart

echo '========================='
echo '=Set up standby server='
echo '========================='

pg_basebackup -h 127.0.0.1 -D ./standbydb  -R -P -U replication -X s  -p $port_primary

cat << EOF >> ./standbydb/postgresql.conf
port = $port_standby
#primary_slot_name = 'standby_1'
hot_standby_feedback = on
EOF
cat << EOF >> ./standbydb/postgresql.auto.conf
primary_conninfo = 'user=replication host=127.0.0.1 port=5433 dbname=postgres'
EOF

pg_ctl -D ./standbydb/ -w -l standby.log start

echo '==================='
echo '=Set up subscriber='
echo '==================='

initdb -D ./subdb

cat << EOF >> ./subdb/postgresql.conf
port = $port_subscriber
max_wal_senders=500
max_worker_processes=1000
max_replication_slots=500
max_logical_replication_workers=500
EOF

pg_ctl start -D ./subdb -w -l sub.log

echo '--------------------'
echo 'physical replication sanity check'
echo '--------------------'

psql -p $port_primary -d postgres << EOF
create table t1(a int);
insert into t1 values (1),(2),(3);
create publication pub1 for table t1;
EOF

sleep 5;

psql -p $port_standby -d postgres << EOF
select * from t1;
\dRp+
EOF

echo '==================='
echo '=Set up pub-sub'
echo '==================='

# 3rd node subscribes to the publication on the 'standby'

psql -p $port_subscriber -d postgres << EOF
create table t1(a int);
insert into t1 values (99);
create subscription sub1 connection 'port=5434' publication pub1;
EOF

sleep 20;

psql -p $port_subscriber -d postgres << EOF
select * from t1;
EOF

