
MASTER=/Users/pavan/work/DATA/pg-data/fbs-master
SB1=/Users/pavan/work/DATA/pg-data/fbs-standby1
SB2=/Users/pavan/work/DATA/pg-data/fbs-standby2

# Initialize the master data dir
initdb -D $MASTER

echo "port = 5532" >> $MASTER/postgresql.conf
echo "wal_level = hot_standby" >> $MASTER/postgresql.conf
echo "max_wal_senders = 3" >> $MASTER/postgresql.conf
echo "local   replication     pavan                                trust" >> $MASTER/pg_hba.conf

# Start master
pg_ctl -D $MASTER -l master.log start
sleep 5

# Take a base backup for the first standby
pg_basebackup -p 5532 -D $SB1 -x 

echo "port = 5533" >> $SB1/postgresql.conf
echo "wal_level = hot_standby" >> $SB1/postgresql.conf
echo "hot_standby = on" >> $SB1/postgresql.conf
echo "standby_mode = on" >> $SB1/recovery.conf
echo "primary_conninfo = 'application_name=standby1 port=5532 user=pavan'" >> $SB1/recovery.conf

# Start the first standby
pg_ctl -D $SB1 -l sb1.log start
sleep 5

# Take base backup for the second standby
pg_basebackup -p 5533 -D $SB2 -x 

echo "port = 5534" >> $SB2/postgresql.conf
echo "wal_level = hot_standby" >> $SB2/postgresql.conf
echo "standby_mode = on" >> $SB2/recovery.conf
echo "primary_conninfo = 'application_name=standby2 port=5533 user=pavan'" >> $SB2/recovery.conf

# Start the second standby
pg_ctl -D $SB2 -l sb2.log start

# Now stop the master and promote the first standby to be the master
pg_ctl -D $MASTER stop
pg_ctl -D $SB1 promote
sleep 5

# Trying to smart shutdown the second standby now fails. The walsender on the
# first standby gets into an infinite loop taking 100% CPU
pg_ctl -D $SB2 stop
