#!/bin/bash

port_N1=5431
port_N2=5432
port_N3=5433

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

pg_ctl stop -D data_N1
pg_ctl stop -D data_N2
pg_ctl stop -D data_N3

rm -rf data_N* *log

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

initdb -D data_N1 -U postgres

cat << EOF >> data_N1/postgresql.conf
wal_level = logical
port = $port_N1
max_connections = 200
EOF

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

pg_ctl -D data_N1 start -w -l N1.log
psql -U postgres -p $port_N1 -c "CREATE TABLE tbl (id int primary key);"
psql -U postgres -p $port_N1 -c "CREATE PUBLICATION pub FOR ALL TABLES"

echo '========================='
echo '=Set up secondary server='
echo '========================='

pg_basebackup -D data_N2 -U postgres -p $port_N1

cat << EOF >> data_N2/postgresql.conf
port = $port_N2
primary_conninfo = 'user=postgres port=$port_N1 application_name=secondary'
hot_standby = on
max_prepared_transactions = 10
EOF

cat << EOF >> data_N2/standby.signal
EOF

pg_ctl -D data_N1   restart -w -l N1.log
pg_ctl -D data_N2 start   -w -l N2.log

cat << EOF >> data_N2/postgresql.conf
hot_standby_feedback = 'on'
EOF

pg_ctl -D data_N1   reload
pg_ctl -D data_N2 reload

echo '==================='
echo '=Set up subscirber='
echo '==================='

echo 'node1 -(physical replication)-> node2 -(logical replication)-> node3'


initdb -U postgres -D data_N3

cat << EOF >> data_N3/postgresql.conf
port = $port_N3
wal_level = logical
max_prepared_transactions = 10
EOF

pg_ctl start -D data_N3 -l N3.log

psql -U postgres -p $port_N3 -c "CREATE TABLE tbl (id int primary key);"
psql -U postgres -p $port_N3 -c "CREATE SUBSCRIPTION sub CONNECTION 'user=postgres dbname=postgres port=$port_N2' PUBLICATION pub WITH (copy_data = false)"
sleep 1

echo '========================'
echo '=INSERT data on primary='
echo '========================'

psql -U postgres -p $port_N1 -c "INSERT INTO tbl VALUES (generate_series(1, 5))"
sleep 1


psql -U postgres -p $port_N2 -c "SELECT slot_name, confirmed_flush_lsn FROM pg_replication_slots"
pg_ctl -D data_N2 restart   -w -l N2.log
psql -U postgres -p $port_N2 -c "SELECT slot_name, confirmed_flush_lsn FROM pg_replication_slots"

