#!/bin/bash

port_old=5431
port_new=5432
bindir=/home/hayato/mypostgres/bin/

echo 'Clean up'

pg_ctl stop -D data_N2
pg_ctl stop -D data_N1

rm -rf data_* *log

echo 'Set up'

initdb -D data_N1 -U postgres
initdb -D data_N2 -U postgres

cat << EOF >> data_N1/postgresql.conf
wal_level = logical
port = $port_old
EOF

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

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

(
    echo -e "SELECT * FROM pg_create_logical_replication_slot('old', 'test_decoding');"
) | psql -U postgres -p $port_old

(
    echo -e "SELECT * FROM pg_create_logical_replication_slot('new', 'test_decoding');"
    echo -e "CREATE DATABASE tmp"
) | psql -U postgres -p $port_new

(
    echo -e "SELECT * FROM pg_create_logical_replication_slot('new_on_tmp', 'test_decoding');"
) | psql -U postgres -p $port_new -d tmp

sleep 1s

pg_ctl stop -D data_N1
pg_ctl stop -D data_N2

pg_upgrade -b $bindir -B $bindir -d data_N1/ -D data_N2/ -r -U postgres
pg_ctl start -D data_N2 -l N2.log

(
    echo -e "SELECT * FROM pg_replication_slots;"
    echo -e "SELECT * FROM pg_logical_slot_get_changes('new_on_tmp', NULL, NULL);"
) | psql -U postgres -p $port_new -d tmp
