#!/bin/bash

port_primary=5431
port_subscriber=5432

echo '=========='
echo '=Clean up='
echo '=========='

pg_ctl stop -D data_primary
pg_ctl stop -D data_subscriber

rm -rf data_* *log

echo '======================='
echo '=Set up primary server='
echo '======================='

initdb -D data_primary -U postgres

cat << EOF >> data_primary/postgresql.conf
wal_level = logical
port = $port_primary
# log_min_duration_statement = 0
EOF

pg_ctl -D data_primary start -w -l primary.log
psql -U postgres -p $port_primary -c "CREATE TABLE tab_1 (a int);"
psql -U postgres -p $port_primary -c "SELECT pg_create_logical_replication_slot('slot1', 'pgoutput', false, false);"
psql -U postgres -p $port_primary -c "CREATE PUBLICATION tap_pub"

initdb -U postgres -D data_subscriber

cat << EOF >> data_subscriber/postgresql.conf
port = $port_subscriber
wal_level = logical
EOF

pg_ctl start -D data_subscriber -l subscriber.log

psql -U postgres -p $port_subscriber -c "CREATE TABLE tab_1 (a int);"
psql -U postgres -p $port_subscriber -c "CREATE SUBSCRIPTION tap_sub CONNECTION 'user=postgres dbname=postgres port=$port_primary' PUBLICATION tap_pub WITH (enabled = true, create_slot = false, slot_name='slot1');"

sleep 2s

for i in `seq 1 20`
do
    psql -U postgres -p $port_primary -c "INSERT INTO tab_1 SELECT generate_series(1, 1000)" &
done

psql -U postgres -p $port_primary -c "ALTER PUBLICATION tap_pub ADD TABLE tab_1;"
psql -U postgres -p $port_subscriber -c "ALTER SUBSCRIPTION tap_sub REFRESH PUBLICATION;"

for i in `seq 21 40`
do
    psql -U postgres -p $port_primary -c "INSERT INTO tab_1 SELECT generate_series(1, 1000)"
done

sleep 2s

psql -U postgres -p $port_primary -c "SELECT count(1) FROM tab_1;"
psql -U postgres -p $port_subscriber -c "SELECT count(1) FROM tab_1;"
