#!/bin/bash

set -e

bin/initdb -D data-master

mkdir -p archivedir

echo "max_wal_senders = 5" >> data-master/postgresql.conf
echo "wal_level = hot_standby" >> data-master/postgresql.conf
echo "wal_keep_segments = 20" >> data-master/postgresql.conf
echo "archive_command='cp %p $PWD/archivedir/%f'" >> data-master/postgresql.conf
echo "archive_mode='on'" >> data-master/postgresql.conf



echo "local   replication     heikki         trust" >> data-master/pg_hba.conf

bin/pg_ctl -w -D data-master start

bin/pg_basebackup -D data-standby

echo "standby_mode=on" >> data-standby/recovery.conf
echo "restore_command='cp $PWD/archivedir/%f %p'" >> data-standby/recovery.conf
echo "recovery_target_timeline = 'latest'" >> data-standby/recovery.conf

echo "hot_standby=on" >> data-standby/postgresql.conf

cp -a data-standby data-standby2

echo "log_line_prefix='S1 '" >> data-standby/postgresql.conf
echo "port=5433" >> data-standby/postgresql.conf
echo "log_line_prefix='S2 '" >> data-standby2/postgresql.conf
echo "port=5434" >> data-standby2/postgresql.conf

echo "primary_conninfo='port=5432'" >> data-standby/recovery.conf
echo "primary_conninfo='port=5433'" >> data-standby2/recovery.conf

bin/pg_ctl -D data-standby start
bin/pg_ctl -D data-standby2 start

echo "log_line_prefix='M  '" >> data-master/postgresql.conf
bin/pg_ctl -w -D data-master reload
