#!/bin/bash

# set -e

port_pub=5431
port_sub=5432
bindir=/usr/local/pgsql/bin/

echo 'Clean up'

pg_ctl stop -D data_N2
pg_ctl stop -D data_N1

rm -r data_* *log

echo 'Set up'

initdb -D data_N1 -U postgres

cat << EOF >> data_N1/postgresql.conf
wal_level = logical
port = $port_pub
log_min_duration_statement = 0
max_wal_senders = '8'
max_replication_slots = '6'
hot_standby_feedback = 'on'
max_prepared_transactions = '10'
max_locks_per_transaction = '512'
EOF

pg_ctl -D data_N1 start -w -l N1.log

(
    echo -e "CREATE TABLE tbl (a int primary key);"
    echo -e "INSERT INTO tbl VALUES (generate_series(1,10));"
) | psql -U postgres -p $port_pub

pg_basebackup -X stream -S 'physical_slot' -C -D data_N2 -U postgres -p $port_pub -R

cat << EOF >> data_N2/postgresql.conf
port = $port_sub
primary_slot_name = 'physical_slot'
EOF

(
    echo -e "INSERT INTO tbl VALUES (generate_series(11, 20));"
) | psql -U postgres -p $port_pub

pg_ctl start -D data_N2 -l N2.log

pg_createsubscriber -d postgres -r -D data_N2/ -P "user=postgres port=$port_pub" -S "user=postgres port=$port_sub" -v -v
