#!/bin/bash

port_publisher=5431
port_subscriber=5432
bindir=/usr/local/pgsql/bin/

echo '##########'
echo '#Clean up#'
echo '##########'

pg_ctl stop -D data_N1
pg_ctl stop -D data_N2
pg_ctl stop -D data_N3

rm -r data_N* *log

echo '########'
echo '#Set up#'
echo '########'

# Set wal_segment_size to small size to lose WALs easily

initdb -D data_N1 -U postgres --wal-segsize=1
initdb -D data_N2 -U postgres --wal-segsize=1
initdb -D data_N3 -U postgres --wal-segsize=1

# Set max_slot_wal_keep_size and max_wal_size to small size

cat << EOF >> data_N1/postgresql.conf
wal_level = logical
port = $port_publisher
min_wal_size = 2MB
max_wal_size = 4MB
max_slot_wal_keep_size = 6MB
EOF

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

cat << EOF >> data_N3/postgresql.conf
wal_level = logical
port = $port_publisher
min_wal_size = 2MB
max_wal_size = 4MB
max_slot_wal_keep_size = 6MB
EOF

# Boot database instances

pg_ctl -D data_N1 start -w -l N1.log
pg_ctl -D data_N2 start -w -l N2.log

# Setup as publisher/subscriber

(
    echo "CREATE TABLE tbl (a int, b int);"
    echo "CREATE PUBLICATION pub FOR TABLE tbl;"
) | psql -U postgres -p $port_publisher

(
    echo "CREATE TABLE tbl (a int, b int);"
    echo "CREATE SUBSCRIPTION sub CONNECTION 'user=postgres dbname=postgres port=$port_publisher' PUBLICATION pub WITH (copy_data = off)"
) | psql -U postgres -p $port_subscriber

# Disable subscriber once

psql -U postgres -p $port_subscriber -c "ALTER SUBSCRIPTION sub DISABLE"

# Advance WAL records to invalidate restart_lsn

for i in {1..10}
do
    psql -U postgres -p $port_publisher -c "CREATE TABLE t (); DROP TABLE t; SELECT pg_switch_wal();"
done

# Make sure the slot is lost
psql -U postgres -p $port_publisher -c "SELECT slot_name, wal_status FROM pg_replication_slots"



###
### testcase a. try to drop sub. before upgrading
###

# Enable the subscription

#psql -U postgres -p $port_subscriber -c "ALTER SUBSCRIPTION sub ENABLE"

# Try to drop the subscirption and will OK

#psql -U postgres -p $port_subscriber -c "DROP SUBSCRIPTION sub"



###
### testcase b. try to drop sub. after upgrading
###

pg_ctl stop -D data_N1 -w
pg_upgrade -b $bindir -B $bindir -d data_N1/ -D data_N3/ -r -U postgres --include-logical-replication-slots
pg_ctl -D data_N3 start -w -l N3.log

# Enable the subscription

psql -U postgres -p $port_subscriber -c "ALTER SUBSCRIPTION sub ENABLE"

# Try to drop the subscription, but will fail...

psql -U postgres -p $port_subscriber -c "DROP SUBSCRIPTION sub"

# Workaround: deassociate the slot from the subscription

#(
#    echo "ALTER SUBSCRIPTION sub DISABLE;"
#    echo "ALTER SUBSCRIPTION sub SET (slot_name = NONE);"
#    echo "DROP SUBSCRIPTION sub"
#) | psql -U postgres -p $port_subscriber
