#!/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
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

# Time to fork nodes
psql -c 'CREATE TABLE aa AS SELECT generate_series(1,100000) AS a'
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
pg_rewind -D $MASTER_DATA --source-server="port=5433" &
sleep 1
# This will make the file list inconsistent
psql -c 'DROP TABLE aa' -p 5433
