#!/bin/bash

port_N1=5431
port_N2=5432
loop=500

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
EOF

cat << EOF >> data_N2/postgresql.conf
wal_level = logical
port = $port_N2
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 "CREATE PUBLICATION pub FOR ALL TABLES WITH (publish='update')"

for ((i=0; i<$loop; i++))
do
    psql -U postgres -p $port_N1 -c "CREATE TABLE tbl_$i (id int primary key)"
    psql -U postgres -p $port_N2 -c "CREATE TABLE tbl_$i (id int primary key)"
done

psql -U postgres -p $port_N2 -c "CREATE SUBSCRIPTION sub CONNECTION 'user=postgres dbname=postgres port=$port_N1' PUBLICATION pub WITH (copy_data=off, two_phase = 'on')"

query=""

for ((i=0; i<$loop; i++))
do
    query+="INSERT INTO tbl_$i VALUES ($i); "
done

psql -U postgres -p $port_N1 -c "$query"
