#!/usr/bin/env bash

./pg_ctl stop -D subscriber -m immediate
./pg_ctl stop -D publisher -m immediate
./pg_ctl stop -D publisher1 -m immediate
rm -rf publisher publisher.log subscriber subscriber.log publisher1 publisher1.log 

mkdir publisher subscriber
./initdb -D publisher
./initdb -D publisher1
./initdb -D subscriber

cat << EOF >> publisher/postgresql.conf
wal_level = logical
max_wal_senders = 10
wal_sender_timeout = 0
max_prepared_transactions = 10
EOF

cat << EOF >> publisher1/postgresql.conf
wal_level = logical
max_wal_senders = 10
wal_sender_timeout = 0
max_prepared_transactions = 10
port = 8888
EOF

cat << EOF >> subscriber/postgresql.conf
wal_level = logical
port = 9999
wal_receiver_timeout = 0
max_prepared_transactions = 10
EOF

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

# setup of pub
./psql -d postgres -c "CREATE TABLE do_write(id serial);"
./psql -d postgres -c "INSERT INTO do_write VALUES(generate_series(1,10));"
./psql -d postgres -c "CREATE PUBLICATION mypub FOR TABLE do_write;"

# setup of pub
./psql -d postgres -p 8888 -c "CREATE TABLE do_write(id serial);"
./psql -d postgres -p 8888 -c "INSERT INTO do_write VALUES(generate_series(1,10));"
./psql -d postgres -p 8888 -c "CREATE PUBLICATION mypub FOR TABLE do_write;"

# setup of sub
./psql -d postgres -p 9999 -c "CREATE TABLE do_write(id serial);"

# create subscription
./psql -d postgres -p 9999 -c "CREATE SUBSCRIPTION mysub CONNECTION 'host=localhost port=5432 dbname=postgres' PUBLICATION mypub WITH (two_phase = true);"

./pg_ctl stop -D publisher -l publisher.log
./pg_ctl stop -D publisher1 -l publisher1.log

cat << EOF >> publisher/postgresql.conf
synchronous_standby_names = mysub
EOF

cat << EOF >> publisher1/postgresql.conf
synchronous_standby_names = mysub
EOF

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

sleep 10

# prepare & commit prepared at publisher
./psql -d postgres -c \
"begin; insert into do_write values (100); prepare transaction 'test1';"

./psql -d postgres -p 9999 -c "Drop subscription mysub;"
./psql -d postgres -p 9999 -c "CREATE SUBSCRIPTION mysub CONNECTION 'host=localhost port=8888 dbname=postgres' PUBLICATION mypub WITH (two_phase = true);"

sleep 10

./psql -d postgres -p 8888  -c \
"begin; insert into do_write values (100); prepare transaction 'test2';"

./psql -d postgres -p 9999 -c "select * from pg_prepared_xacts;"

