#!/bin/bash
# Test pg_rewind stuff

MASTER_DATA=$HOME/data/5432
STANDBY_DATA=$HOME/data/5433

# Create cluster
rm -r $MASTER_DATA $STANDBY_DATA
initdb -D $MASTER_DATA > /dev/null 2>&1
cat >> $MASTER_DATA/postgresql.conf <<EOF
wal_level = hot_standby
wal_log_hints = on
max_wal_senders = 10
hot_standby = on
wal_keep_segments = 25
EOF
cat >> $MASTER_DATA/pg_hba.conf <<EOF
host replication $USER 127.0.0.1/32 trust
host replication $USER ::1/128 trust
local replication $USER trust
EOF
pg_ctl start -s -w -D $MASTER_DATA
createdb $USER > /dev/null 2>&1
pg_basebackup -D $STANDBY_DATA -p 5432 -R > /dev/null 2>&1
cat >> $STANDBY_DATA/postgresql.conf <<EOF
port = 5433
EOF
pg_ctl start -s -w -D $STANDBY_DATA

# Create a bunch of objects able to trigger a failure
psql -Atq -c 'CREATE TABLE aa (a int)'
for i in {1..10}; do
	psql -Atq -c 'INSERT INTO aa VALUES (generate_series(1,1000))'
done
sleep 2 # Let room to replay

# Time to fork
pg_ctl promote -s -D $STANDBY_DATA -w
sleep 2
psql -Atq -c 'INSERT INTO aa VALUES (generate_series(1,2000))'
psql -Atq -c 'INSERT INTO aa VALUES (generate_series(1,3000))' -p 5433
sleep 2

pg_ctl stop -s -D $STANDBY_DATA
pg_ctl stop -s -D $MASTER_DATA

# Put back standby node behind master
pg_rewind --source-pgdata=$MASTER_DATA --target-pgdata=$STANDBY_DATA
