#!/bin/bash

# first argument: number of slots
# first argument: number of workers

port_publisher=5431
bindir=~/mypostgres/bin/

declare num_slots
if [ -n "$1" ]; then
    num_slots=$1
else
    num_slots=10
fi

declare num_worker
if [ -n "$2" ]; then
    num_worker=$2
else
    num_worker=1
fi

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
initdb -D data_N3 -U postgres

# 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
max_replication_slots = $num_slots
EOF

cat << EOF >> data_N3/postgresql.conf
wal_level = logical
port = $port_publisher
max_replication_slots = $num_slots
EOF

# Boot database instances

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

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

for i in `seq 1 $num_slots`
do
    psql -U postgres -p $port_publisher -c "SELECT * FROM pg_create_logical_replication_slot('test_${i}', 'test_decoding')"
done

for i in `seq 1 $num_slots`
do
    psql -U postgres -p $port_publisher -c "SELECT * FROM pg_logical_slot_get_changes('test_${i}', NULL, NULL);"
done

pg_ctl stop -D data_N1 -w
pg_upgrade -b $bindir -B $bindir -d data_N1/ -D data_N3/ -r -U postgres -p $port_publisher -j $num_worker
pg_ctl start -D data_N3 -l N3.log

psql -U postgres -p 5431 -c "SELECT count(*) FROM pg_replication_slots"

