#!/bin/bash

port_N1=5431
port_N2=5432

echo 'Clean up'

pg_ctl stop -D data_N2
pg_ctl stop -D data_N1

rm -rf data_* *log

echo 'Set up'

initdb -D data_N1 -U postgres

cat << EOF >> data_N1/postgresql.conf
wal_level = logical
port = $port_N1
track_commit_timestamp = on
EOF

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

(
     echo -e "
create table tab (a int primary key);
insert into tab values (1);
create publication pub for table tab;
"
) | psql -U postgres -p $port_N1

initdb -D data_N2 -U postgres

cat << EOF >> data_N2/postgresql.conf
wal_level = logical
port = $port_N2
track_commit_timestamp = on
wal_receiver_status_interval = 1s
wal_sender_timeout = 300s     ## to avoid walsender timeout while waiting for slot's xmin advance.
EOF

pg_ctl -D data_N2 start -w -l N2.log

(
     echo -e "
create table tab (a int primary key);
create publication pub for table tab;
create subscription sub12 connection 'user=postgres port=$port_N1' publication pub with (copy_data = on, origin=none, detect_update_deleted = true);
"
) | psql -U postgres -p $port_N2

(
     echo -e "
create subscription sub21 connection 'user=postgres port=$port_N2' publication pub with (copy_data = off, origin=none, detect_update_deleted = true);
"
) | psql -U postgres -p $port_N1
