#!/bin/bash
# Test pg_rewind failure
# Triggers pg_rewind error:
# could not open file "base/16384/16385_fsm"

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

# Create cluster
rm -r $MASTER_DATA $STANDBY_DATA
initdb -D $MASTER_DATA
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 -w -D $MASTER_DATA
createdb $USER
pg_basebackup -D $STANDBY_DATA -p 5432 -R
cat >> $STANDBY_DATA/postgresql.conf <<EOF
port = 5433
EOF
pg_ctl start -w -D $STANDBY_DATA

# Create a bunch of objects able to trigger a failure
psql -c 'CREATE TABLE aa AS SELECT generate_series(1,100000) AS a'
sleep 2 # Let room to replay

# Time to fork
pg_ctl promote -D $STANDBY_DATA
psql -c 'INSERT INTO aa VALUES (generate_series(1,10000))'
sleep 2
psql -c 'INSERT INTO aa VALUES (generate_series(1,20000))' -p 5433

# And rewind in batch, rewind will sleep a bit..
pg_ctl stop -D $MASTER_DATA -w
pg_ctl restart -D $STANDBY_DATA -w

# Execute rewind in batch and let time to remove objects
pg_rewind -D $MASTER_DATA --source-server="port=5433" --progress --debug > ~/Desktop/rewind_log.txt 2>&1 &
sleep 1

# Remove all objects
psql -c 'DROP TABLE IF EXISTS aa' -p 5433

# Let pg_rewind finish
sleep 10
echo "Sleep time is over"
echo "port = 5432" >> $MASTER_DATA/postgresql.conf
cat >> $MASTER_DATA/recovery.conf <<EOF
standby_mode = 'on'
primary_conninfo = 'user=ioltas port=5433 sslmode=prefer sslcompression=1'
EOF
# Plug-in back master
pg_ctl start -w -D $MASTER_DATA
