#!/bin/bash

PG_PRIMARY_PORT=5450
PG_STANDBY_PORT=5451

# Cleanup anything left over from previous runs.
for d in pgprimary pgstandby; do
    if test -d $d; then
		pg_ctl stop -D $d;
		rm -rf $d
	fi
	rm -f $d.log
done

# Echo commands from this point onward and exit on failure.
set -ex

# Initialize and Create primary.
# NB: Must enable archiving, but only for history files not WAL files.
initdb -D pgprimary --encoding=UTF8 --no-locale

# Create WAL archive directory
mkdir -p pgprimary/arc

cat >> pgprimary/postgresql.auto.conf <<EOM
port=$PG_PRIMARY_PORT
archive_mode=always
archive_command = 'test ! -f arc/%f && cp %p arc/%f'
restore_command = 'cp arc/%f %p'
recovery_target_timeline = 'latest'
EOM

#1 Start pgprimary as a main
pg_ctl start -D pgprimary -l pgprimary.log

#2 Create standby
pg_basebackup -D pgstandby -R -d "port=$PG_PRIMARY_PORT"
cat >> pgstandby/postgresql.auto.conf <<EOM
port=$PG_STANDBY_PORT
archive_mode=always
archive_command = 'test ! -f arc/%f && cp %p arc/%f'
restore_command = 'cp arc/%f %p'
recovery_target_timeline = 'latest'
EOM

#3 Start pgstandby as a standby
touch pgstandby/standby.signal
pg_ctl start -D pgstandby -l pgstandby.log
sleep 3

#4 Execute archive command
ls -l pgprimary/arc
psql -p $PG_PRIMARY_PORT -c "create table test (a int);"
# These are the trigger for archive_command
psql -p $PG_PRIMARY_PORT -c "insert into test values (1); checkpoint; select pg_switch_wal();"  # OK
psql -p $PG_PRIMARY_PORT -c "insert into test values (1); checkpoint; select pg_switch_wal();"  # OK
psql -p $PG_PRIMARY_PORT -c "insert into test values (1); checkpoint; select pg_switch_wal();"  # OK
sleep 3
ls -l pgprimary/arc

#5 Shutdown pgprimary
pg_ctl stop -D pgprimary
sleep 3

#6 Start pgprimary as a standby
touch pgprimary/standby.signal
pg_ctl start -D pgprimary -l pgprimary.log
sleep 3

#7 Promote pgprimary
pg_ctl promote -D pgprimary
sleep 10

#8 Execute archive_command again, but failed since duplicate history file exist (see pgstandby.log)
ls -l pgprimary/arc
ls -l pgstandby/arc
# These are the trigger for archive_command
echo "---- NG ---- (If we use archive_mode=on, archive_command is successful)"
psql -p $PG_PRIMARY_PORT -c "insert into test values (1); checkpoint; select pg_switch_wal();"  # NG: archive_command failed
psql -p $PG_PRIMARY_PORT -c "insert into test values (1); checkpoint; select pg_switch_wal();"  # NG: archive_command failed
psql -p $PG_PRIMARY_PORT -c "insert into test values (1); checkpoint; select pg_switch_wal();"  # NG: archive_command failed
ls -l pgprimary/arc
ls -l pgstandby/arc

exit

