#!/bin/bash

port_N1=5431
port_N2=5432

common_tbl="CREATE TABLE tbl (id int PRIMARY KEY, c timestamptz DEFAULT now());"

echo 'Clean up'

pg_ctl stop -D data_N2
pg_ctl stop -D data_N1

rm -r data_N1 data_N2 *log

echo 'Set up'

initdb -D data_N1 -U postgres
initdb -D data_N2 -U postgres

cat << EOF >> data_N1/postgresql.conf
wal_level = logical
port = $port_N1
logical_decoding_work_mem = 64kB
wal_sender_timeout = 13s
log_min_messages = debug2
EOF

cat << EOF >> data_N2/postgresql.conf
wal_level = logical
port = $port_N2
wal_receiver_status_interval = 10s
log_min_messages = debug2
EOF

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

psql -U postgres -p $port_N1 -c "$common_tbl"
psql -U postgres -p $port_N2 -c "$common_tbl"

psql -U postgres -p $port_N1 -c "CREATE PUBLICATION pub FOR TABLE tbl (id)"

psql -U postgres -p $port_N2 -c "CREATE SUBSCRIPTION sub CONNECTION 'user=postgres dbname=postgres port=$port_N1' PUBLICATION pub WITH (copy_data=false, origin='none', streaming='off', min_apply_delay = '8s')"

sleep 6s

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