#!/bin/bash

PG_PRIMARY_PORT=5450
PG_STANDBY_PORT=5451
PG_CASCADE_PORT=5452

# Cleanup anything left over from previous runs.
for d in pgprimary pgstandby pgstandby2; do
    if test -d $d; then
		pg_ctl stop -D $d;
		rm -rf $d
	fi
	rm -f $d.log
done
rm -rf wal_archive
rm -rf wal_archive1
# Echo commands from this point onward and exit on failure.
set -ex

# Create empty WAL archive.
mkdir wal_archive
mkdir wal_archive1

# Initialize and start primary.
# NB: Must enable archiving, but only for history files not WAL files.
initdb -D pgprimary
cat >> pgprimary/postgresql.auto.conf <<EOM
port=$PG_PRIMARY_PORT
archive_mode=on
archive_command='`pwd`/recalcitrant_cp %p `pwd`/wal_archive/%f'
EOM
pg_ctl start -D pgprimary -l pgprimary.log

# Create standby.
pg_basebackup -D pgstandby -R -d "port=$PG_PRIMARY_PORT"
cat >> pgstandby/postgresql.auto.conf <<EOM
port=$PG_STANDBY_PORT
archive_mode=on
archive_command='`pwd`/recalcitrant_cp %p `pwd`/wal_archive1/%f'
EOM
pg_ctl start -D pgstandby -l pgstandby.log

# Create cascading standby but don't start it yet.
# NB: Use -Xnone so that pg_wal is empty.
# NB: Must set up both streaming and archiving.
pg_basebackup -D pgstandby2 -R -d "port=$PG_PRIMARY_PORT"
cat >> pgstandby2/postgresql.auto.conf <<EOM
port=$PG_CASCADE_PORT
restore_command='cp `pwd`/wal_archive/%f %p'
EOM
pg_ctl start -D pgstandby2 -l pgstandby2.log

# Promote the standby. Give it a few seconds to archive the history file.
pg_ctl promote -D pgstandby
sleep 2

pg_ctl stop -D pgstandby2 -l pgstandby2.log
rm -rf pgstandby2/pg_wal/*

cat >> pgstandby2/postgresql.auto.conf <<EOM
primary_conninfo='port=5451'
restore_command='cp `pwd`/wal_archive1/%f %p'
EOM
# Now start the cascading standby.
pg_ctl start -D pgstandby2 -l pgstandby2.log
