#!/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
max_prepared_transactions = 10
log_min_messages = debug2
log_replication_commands = on
EOF
pg_ctl -D data_N1 start -w -l N1.log

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

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

(
    echo -e "CREATE TABLE foo (a int PRIMARY KEY);"
    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

# Please PREPARE a transaciton after attaching the walwriter process to avoid unexpected WAL flush
#(
#    echo -e "BEGIN; INSERT INTO foo VALUES (generate_series(1, 5)); PREPARE TRANSACTION 'txn1';"
#) | psql -U postgres -p $port_1
