#!/bin/bash

port_N1=5431
port_N2=5432

echo 'Clean up'

pg_ctl stop -D data_N1
pg_ctl stop -D data_N2

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
max_logical_replication_workers=100
max_replication_slots=40
autovacuum = off
max_prepared_transactions = 10
log_min_duration_statement = 0
logical_decoding_work_mem = 64kB
EOF

cat << EOF >> data_N2/postgresql.conf
wal_level = logical
port = $port_N2
max_logical_replication_workers=100
max_replication_slots=40
autovacuum = off
max_prepared_transactions = 10
log_min_duration_statement = 0
wal_retrieve_retry_interval = 1ms
enable_bitmapscan = off
#log_min_messages = 'debug3'
exit_on_error = on
restart_after_crash = off
EOF

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

psql -U postgres -p $port_N1 -c "create table tbl(id int4, p point);"
psql -U postgres -p $port_N1 -c "ALTER TABLE tbl REPLICA IDENTITY FULL;"
psql -U postgres -p $port_N1 -c "CREATE PUBLICATION pub FOR ALL TABLES"

psql -U postgres -p $port_N1 -c "insert into tbl (id, p) select g, point(g*10, g*10) from generate_series(1, 10000) g;"

psql -U postgres -p $port_N2 -c "create table tbl(id int4, p point);"
psql -U postgres -p $port_N2 -c "CREATE SUBSCRIPTION sub CONNECTION 'user=postgres dbname=postgres port=$port_N1' PUBLICATION pub WITH (copy_data = 'on', origin='none', streaming = 'on')"

sleep 2s
psql -U postgres -p $port_N1 -c "delete from tbl where id % 2 = 1;"

