#!/bin/bash

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

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

pg_ctl stop -D data_N1
pg_ctl stop -D data_N3

rm -r data_N* *log

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

initdb -D data_N1 -U postgres
initdb -D data_N3 -U postgres

cat << EOF >> data_N1/postgresql.conf
wal_level = logical
port = $port_publisher
log_min_duration_statement = 0
EOF

cat << EOF >> data_N3/postgresql.conf
wal_level = logical
port = $port_publisher
log_min_duration_statement = 0
EOF

# Boot database instance

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

# Setup

(
    echo "SELECT * FROM pg_create_logical_replication_slot('slot', 'pgoutput');"
    echo "SELECT * FROM pg_replication_slots"
) | psql -U postgres -p $port_publisher

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

# Confirmed there are no tables on new publisher, whereas it was created on old one

(
    echo "\d"
) | psql -U postgres -p $port_publisher
