#!/bin/sh

PGBIN=bin

$PGBIN/initdb -D master
cat >> master/postgresql.conf <<EOF
wal_level = hot_standby
max_wal_senders = 4
wal_keep_segments = 32
hot_standby = on
EOF
echo "local replication postgres trust" >> master/pg_hba.conf

$PGBIN/pg_ctl -D master -w start
$PGBIN/pg_basebackup -D standby1 -c fast
echo "port = 5433" >> standby1/postgresql.conf
cat > standby1/recovery.conf <<EOF
standby_mode = on
primary_conninfo = 'port=5432'
recovery_target_timeline = 'latest'
EOF

$PGBIN/pg_ctl -D standby1 -w start
$PGBIN/pg_basebackup -D standby2 -c fast -p 5433
echo "port = 5434" >> standby2/postgresql.conf
cat > standby2/recovery.conf <<EOF
standby_mode = on
primary_conninfo = 'port=5433'
recovery_target_timeline = 'latest'
EOF

$PGBIN/pg_ctl -D standby2 -w start
$PGBIN/pg_ctl -D master stop
$PGBIN/pg_ctl -D standby1 promote
sleep 5

$PGBIN/pg_basebackup -D standby3 -c fast -p 5434
echo "port = 5435" >> standby3/postgresql.conf
cat > standby3/recovery.conf <<EOF
standby_mode = on
primary_conninfo = 'port=5434'
recovery_target_timeline = 'latest'
EOF

$PGBIN/pg_ctl -D standby3 start
