#!/bin/bash
#
# A quick and dirty script to stand up a bunch of streaming replicas
# for testing the synchronous replay 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=3

rm -fr $DATA_DIR

# set up primary
$INSTALL/bin/initdb -D $DATA_DIR/primary
cat << EOF >> $DATA_DIR/primary/postgresql.conf
  wal_level = hot_standby
  max_wal_senders = 20
  synchronous_replay_max_lag = 2s
  #synchronous_replay_standby_names = 'replica1, replica2'
  max_prepared_transactions = 10
  log_line_prefix = '[primary ] %m '
EOF
cat << EOF >> $DATA_DIR/primary/pg_hba.conf
  local replication rep_user trust
EOF

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

# set up replicas
for ((I=1;I<=REPLICAS;I++)) ; do
  cp -r $DATA_DIR/primary $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
    log_line_prefix = '[replica$I] %m '
EOF
done

cat << EOF >> $DATA_DIR/primary/postgresql.conf
  cluster_name = primary
EOF

$INSTALL/bin/pg_ctl start -w -D $DATA_DIR/primary
sleep 2

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

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

sleep 600

# shut down
for ((I=1;I<=REPLICAS;I++)) ; do
  $INSTALL/bin/pg_ctl stop -D $DATA_DIR/replica$I
done
sleep 1
$INSTALL/bin/pg_ctl stop -D $DATA_DIR/primary
