#!/bin/bash

port_N1=5431
port_N2=5432

common_tbl="CREATE TABLE tbl (c int primary key);"

echo '****************************************'
echo 'Clean up'
echo '****************************************'

pg_ctl stop -D data_N1
pg_ctl stop -D data_N2

rm -r data_N1 data_N2 *log

echo '****************************************'
echo 'Set up'
echo '****************************************'

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

cat << EOF >> data_N1/postgresql.conf
wal_level = logical
logical_decoding_work_mem = 64kB
port = $port_N1
autovacuum = off
EOF

cat << EOF >> data_N2/postgresql.conf
wal_level = logical
port = $port_N2
autovacuum = off
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_N1 -c "create publication pub for all tables"

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

psql -U postgres -p $port_N2 -c "create subscription sub connection 'port=$port_N1 user=postgres' publication pub with (streaming = 'parallel', copy_data = 'true');"

echo '****************************************'
echo 'Insert huge data'
echo '****************************************'

psql -U postgres -p $port_N1 -c "BEGIN; INSERT INTO tbl SELECT i FROM generate_series(1, 5000000) s(i); COMMIT;"
