#!/bin/bash
#
# A quick and dirty script to stand up a bunch of streaming replicas
# for testing the causal reads patch.

# Where to find the patched Postgres installation
INSTALL=~/install/postgres

# Where to create all the pgdata dirs (blown away each time)
DATA_DIR=~/junk/pgdatas

# Set this to a number between 1 and 9
REPLICAS=4

rm -fr $DATA_DIR

# set up master
$INSTALL/bin/initdb -D $DATA_DIR/master
cat << EOF >> $DATA_DIR/master/postgresql.conf
  wal_level = hot_standby
  max_wal_senders = 20
  causal_reads_timeout = 4s
  causal_reads_standby_names = '*'
EOF
cat << EOF >> $DATA_DIR/master/pg_hba.conf
  local replication rep_user trust
EOF

# set up user, and make sure we have a base-backup at correct wal level
$INSTALL/bin/pg_ctl start -w -D $DATA_DIR/master
$INSTALL/bin/psql postgres -c 'CREATE ROLE rep_user REPLICATION LOGIN'
$INSTALL/bin/pg_ctl stop -D $DATA_DIR/master

# set up replicas
for ((I=1;I<=REPLICAS;I++)) ; do
  cp -r $DATA_DIR/master $DATA_DIR/replica$I
  cat << EOF >> $DATA_DIR/replica$I/recovery.conf
    standby_mode = on
    primary_conninfo = 'user=rep_user application_name=replica$I'
EOF
  cat << EOF >> $DATA_DIR/replica$I/postgresql.conf
    hot_standby = on
    port = 544$I
    cluster_name = replica$I
EOF
done

cat << EOF >> $DATA_DIR/master/postgresql.conf
  cluster_name = master
  #synchronous_standby_names = '*'
EOF

echo XXX starting master
$INSTALL/bin/pg_ctl start -w -D $DATA_DIR/master
sleep 2

for ((I=1;I<=REPLICAS;I++)) ; do
  echo XXX starting replica$I
  $INSTALL/bin/pg_ctl start -D $DATA_DIR/replica$I
  sleep 1
done

$INSTALL/bin/psql postgres -c 'CREATE TABLE foox (data text)'

echo XXX finished
sleep 600

for ((I=1;I<=REPLICAS;I++)) ; do
  echo XXX stopping replica$I
  $INSTALL/bin/pg_ctl stop -D $DATA_DIR/replica$I
done
sleep 1

echo XXX stopping master
$INSTALL/bin/pg_ctl stop -D $DATA_DIR/master
