#!/bin/bash

port_primary=5431
port_standby=5432

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

pg_ctl stop -D data_N2
pg_ctl stop -D data_N1

rm -r data_* *log

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

initdb -D data_N1 -U postgres

cat << EOF >> data_N1/postgresql.conf
wal_level = logical
port = $port_primary
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_primary

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

pg_basebackup -D data_N2 -U postgres -p $port_primary

cat << EOF >> data_N2/postgresql.conf
port = $port_standby
primary_conninfo = 'user=postgres port=$port_primary'
EOF

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

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

pg_ctl start -D data_N2 -l N2.log

psql -U postgres -p $port_standby -c "SELECT pg_is_in_recovery();"

echo '====================================='
echo '===== Start pg_createsubscriber ====='
echo '====================================='

# For v14-0001
pg_createsubscriber -d postgres -r -D data_N2/ -P "user=postgres port=$port_primary" -S "user=postgres port=$port_standby" -v -t 30
