#!/bin/bash

PGPATH=pg-master/bin
PORT1=5450
PORT2=5451

PSQL=$PGPATH/psql
MASTER_PSQL="$PGPATH/psql -h localhost -p ${PORT1} -U postgres"
REPLICA_PSQL="$PGPATH/psql -h localhost -p ${PORT2} -U postgres"

cleanup_datadir() {
	$PGPATH/pg_ctl -D $1 stop
	rm -rf $1
}

msg() {
	echo
	echo
	echo '##' $@
	echo
}

msg "Clean up after previous runs"

if [ -e master ]; then
	cleanup_datadir master
fi
if [ -e replica ]; then
	cleanup_datadir replica
fi

msg "Set up a simple hot standby setup with a replication slot"

$PGPATH/initdb -U postgres --nosync master > /dev/null 2> /dev/null || exit
tee -a master/postgresql.conf > /dev/null <<CONF
wal_level = 'replica'
hot_standby = 'on'
max_replication_slots = 2
max_wal_senders = 2
fsync = off
port = ${PORT1}
CONF
tee -a master/pg_hba.conf > /dev/null <<CONF
host    replication     postgres        127.0.0.1/32            trust
CONF

$PGPATH/pg_ctl -D master -l master/startup.log -w start

$MASTER_PSQL -c "SELECT pg_create_physical_replication_slot('testslot')"

$PGPATH/pg_basebackup -D replica -R -S testslot -X stream -c fast -h localhost -p ${PORT1} -U postgres

sed -i "s/port = ${PORT1}/port = ${PORT2}/" replica/postgresql.conf
$PGPATH/pg_ctl -D replica -l replica/startup.log -w start

msg "Temporarily turn on hot standby feedback"

$REPLICA_PSQL <<SQL
ALTER SYSTEM SET hot_standby_feedback TO on;
SELECT pg_reload_conf();
SQL

msg "Create some WAL traffic, observe replication slot xmin gets set"

$MASTER_PSQL <<SQL
CREATE TABLE test (id serial primary key, tstamp timestamptz default now());
INSERT INTO test DEFAULT VALUES;
SQL

$MASTER_PSQL -c "SELECT slot_name, xmin FROM pg_replication_slots"

msg "Turn off hot standby feedback while replica is shut off"

$REPLICA_PSQL -c "ALTER SYSTEM SET hot_standby_feedback TO off"
$PGPATH/pg_ctl -D replica -l replica/startup.log -w restart

msg "Replication slot xmin on the slot does not get reset, nor updated"

$MASTER_PSQL -c "SELECT slot_name, xmin FROM pg_replication_slots"
$MASTER_PSQL -c "INSERT INTO test DEFAULT VALUES"
sleep 1
$MASTER_PSQL -c "SELECT slot_name, xmin FROM pg_replication_slots"
$MASTER_PSQL -c "DELETE FROM test"
sleep 1

msg "Vacuuming can not remove old rows"

$MASTER_PSQL -c "VACUUM VERBOSE test" 2>&1 | grep nonremovable

msg "Turn hot standby feedback on and off while replica is running"

$REPLICA_PSQL <<SQL
ALTER SYSTEM SET hot_standby_feedback TO on;
SELECT pg_reload_conf();
SQL

sleep 1

$REPLICA_PSQL <<SQL
ALTER SYSTEM SET hot_standby_feedback TO off;
SELECT pg_reload_conf();
SQL

msg "Replication slot xmin gets reset"

$MASTER_PSQL -c "INSERT INTO test DEFAULT VALUES"
$MASTER_PSQL -c "SELECT slot_name, xmin FROM pg_replication_slots"

msg "Vacuum works now"

$MASTER_PSQL -c "VACUUM VERBOSE test" 2>&1 | grep nonremovable
