#!/bin/bash

# set -e

port_1=5431
port_2=5432

echo 'Clean up'

pg_ctl stop -D data_N2
pg_ctl stop -D data_N1

rm -r data_* *log

echo 'Set up'

# Setup and start publisher
initdb -D data_N1 -U postgres
cat << EOF >> data_N1/postgresql.conf
wal_level = logical
port = $port_1
log_replication_commands = true
max_prepared_transactions = 10
EOF
pg_ctl -D data_N1 start -w -l N1.log

(
    echo -e "CREATE TABLE foo (a int PRIMARY KEY);"
    echo -e "CREATE TABLE var (a int);"
    echo -e "CREATE PUBLICATION pub FOR ALL TABLES;"
) | psql -U postgres -p $port_1

# Setup and start subscriber with two_phase = true but max_prepared_transactions = 0
initdb -D data_N2 -U postgres
cat << EOF >> data_N2/postgresql.conf
port = $port_2
max_prepared_transactions = 0
EOF
pg_ctl -D data_N2 start -w -l N2.log

(
    echo -e "CREATE TABLE foo (a int PRIMARY KEY);"
    echo -e "CREATE TABLE var (a int);"
    echo -e "CREATE SUBSCRIPTION sub CONNECTION 'user=postgres port=$port_1' PUBLICATION pub WITH (two_phase=true, copy_data=false);"
) | psql -U postgres -p $port_2

# PREPARE a transaciton. It will fail on the subscriber because max_prepared_transactions is zero.
# Note that this will be replicated only once because the replication origin is updated.
(
    echo -e "BEGIN; INSERT INTO foo VALUES (generate_series(1, 5)); PREPARE TRANSACTION 'txn1';"
) | psql -U postgres -p $port_1

# If the transaction is committed on the publisher's side, the subscriber tries
# to commit the non-existing transaction so that the replication stops.
#(
#    echo -e "COMMIT PREPARED 'txn1';"
#) | psql -U postgres -p $port_1
