#!/bin/bash
#
# This script reproduces the bug reported by Fujii Masao at:
# http://www.postgresql.org/message-id/CAHGQGwEO1GF3=7LAeyn630+PNjjkC4fnwqx_L_Vyq6Y+OsB5jg@mail.gmail.com
#
PATH=/home/heikki/pgsql.master/bin:$PATH
TESTDIR=/home/heikki/pgsql.master

# exit on error
set -e

# Set up master
initdb -D $TESTDIR/data-master
echo "wal_keep_segments=10" >> $TESTDIR/data-master/postgresql.conf
echo "wal_level=hot_standby" >> $TESTDIR/data-master/postgresql.conf
echo "max_wal_senders=5" >> $TESTDIR/data-master/postgresql.conf
echo "log_line_prefix='M  %m %p '" >> $TESTDIR/data-master/postgresql.conf
echo "hot_standby=on" >> $TESTDIR/data-master/postgresql.conf
echo "log_checkpoints=on" >> $TESTDIR/data-master/postgresql.conf

# Accept replication connections
echo "local   replication     heikki                                trust" >> $TESTDIR/data-master/pg_hba.conf

pg_ctl -w -D $TESTDIR/data-master start

# 2. Set up standby B, and cascading standby C

pg_basebackup -D $TESTDIR/data-standbyB
pg_basebackup -D $TESTDIR/data-standbyC

sed -i "s/log_line_prefix=.*/log_line_prefix='B %m %p '/g" $TESTDIR/data-standbyB/postgresql.conf
sed -i "s/log_line_prefix=.*/log_line_prefix='C %m %p '/g" $TESTDIR/data-standbyC/postgresql.conf
echo "port=5433" >> $TESTDIR/data-standbyB/postgresql.conf
echo "port=5434" >> $TESTDIR/data-standbyC/postgresql.conf

cat > $TESTDIR/data-standbyB/recovery.conf <<EOF
primary_conninfo = ''
standby_mode='on'
recovery_target_timeline='latest'
EOF

cat > $TESTDIR/data-standbyC/recovery.conf <<EOF
primary_conninfo = 'port=5433'
standby_mode='on'
recovery_target_timeline='latest'
EOF


# All set
pg_ctl -D data-standbyB -w start
#pg_ctl -D data-standbyC -w start
echo "All servers started."
sleep 2

# Start pgbench init against master, and promote standby B while it's running
pgbench -i -s 10 postgres & 
sleep 2
pg_ctl -D data-standbyB promote

