#!/usr/bin/env bash

./pg_ctl stop -D publisher
rm -rf publisher publisher.log

mkdir publisher
./initdb -D publisher

cat << EOF >> publisher/postgresql.conf
wal_level = logical
listen_addresses = '*'
checkpoint_timeout = '30s'
EOF

cat << EOF >> publisher/pg_hba.conf
host   all all	0.0.0.0/0	trust
EOF

./pg_ctl start -D publisher -l publisher.log

cluster_name=subscriber
./pg_ctl stop -D $cluster_name

rm -rf $cluster_name $cluster_name.log

mkdir $cluster_name
./initdb -D $cluster_name

cat << EOF >> $cluster_name/postgresql.conf
listen_addresses = '*'
port = 9999
EOF

cat << EOF >> $cluster_name/pg_hba.conf
host	all	all	0.0.0.0/0	trust
EOF

./pg_ctl start -D $cluster_name -l $cluster_name.log

sleep 3

./psql -d postgres -c "create table t1(c1 int);"
./psql -d postgres -c "create table t2(c1 int);"
./psql -d postgres -c "create publication pub1 for table t1;"
./psql -d postgres -c "create publication pub2 for table t2;"

sleep 1

./psql -d postgres -p 9999 -c "create table t1(c1 int);"
./psql -d postgres -p 9999 -c "create table t2(c1 int);"
sleep 3
./psql -d postgres -p 9999 -c "create subscription test1 connection 'dbname=postgres host=localhost port=5432' publication pub1, pub2;"
./psql -d postgres -p 9999 -c "select * from pg_subscription"
./psql -d postgres -c "insert into t1 values(10);"
./psql -d postgres -c "insert into t2 values(20);"
sleep 10
./psql -d postgres -c "drop publication pub2;"
./psql -d postgres -c "insert into t1 values(10);"
./psql -d postgres -c "insert into t2 values(20);"
./pg_ctl stop -D publisher

