#!/bin/bash

set -ex

# Cleanup any previous runs
for pgdata in primary primary_restored replica; do
    if [ -f $pgdata/postmaster.pid ]; then
        pg_ctl -D $pgdata -m immediate stop
    fi
done
rm -rf archive {primary,primary_restored,replica}{,.log}

# Set up primary and do a backup
initdb primary
mkdir archive
tee primary/postgresql.conf <<EOF
port = 5434
archive_mode = on
archive_command = 'cp %p ../archive/'
EOF
pg_ctl -D primary/ -l primary.log start
psql -p 5434 -f - postgres <<EOF
CREATE TABLE test (msg text);
CREATE TABLE test2 (msg text);
EOF
pg_basebackup -p 5434 -c fast -D primary_restored

# Some additional WAL traffic after backup
psql -p 5434 -f - postgres <<EOF
INSERT INTO test VALUES ('I should not be restored');
EOF


# Stop primary and create a copy of the backup 
pg_ctl -D primary stop
cp -ar primary_restored/ replica/

# Start primary from backup with recovery_target = 'immediate'
tee primary_restored/postgresql.conf <<EOF
port = 5434
archive_mode = on
archive_command = 'cp %p ../archive/'
restore_command = 'cp ../archive/%f %p'
recovery_target = 'immediate'
recovery_target_action = 'promote'
EOF
touch primary_restored/recovery.signal
pg_ctl -D primary_restored/ -l primary_restored.log start

sleep 1 && cat primary_restored.log

# History file is archived
cat archive/00000002.history


# Start replica from same backup
tee replica/postgresql.conf <<EOF
port = 5435
archive_mode = on
archive_command = 'cp %p ../archive/'
restore_command = 'cp ../archive/%f %p'
primary_conninfo = 'port=5434'
EOF
touch replica/standby.signal

(psql -p 5434 -f - postgres <<EOF
INSERT INTO test VALUES ('I should be present');
SELECT pg_sleep(5);
SELECT pg_switch_wal();
INSERT INTO test2 VALUES ('I am same length as nr1');
SELECT pg_switch_wal();
EOF
)&


pg_ctl -D replica/ -l replica.log start
sleep 10

echo "On primary"
psql -p 5434 postgres -c 'TABLE test' -c 'TABLE test2'

echo "On replica"
psql -p 5435 postgres -c 'TABLE test' -c 'TABLE test2'

