#!/bin/bash
echo "Cleaning.."
rm -rf *_logfile
rm /tmp/failover.log
rm -rf /tmp/archive_dir
mkdir /tmp/archive_dir

export PGPORT=5432			#MASTER PORT
PGSQL_DIR=$(pwd)
PGSQL_BIN=$PGSQL_DIR/bin
PGSQL_MASTER=$PGSQL_DIR/master		#DATA FOLDER FOR PRIMARY/MASTER SERVER
PGSQL_STANDBY=$PGSQL_DIR/standby	#DATA FOLDER FOR BACKUP/STANDBY SERVER

#Cleanup the master and slave data directory and create a new one.
rm -rf $PGSQL_MASTER $PGSQL_STANDBY
mkdir $PGSQL_MASTER $PGSQL_STANDBY
chmod 700 $PGSQL_MASTER
chmod 700 $PGSQL_STANDBY

#Initialize MASTER
$PGSQL_BIN/initdb -D $PGSQL_MASTER
echo "wal_level = hot_standby" >> $PGSQL_MASTER/postgresql.conf
echo "max_wal_senders = 3" >> $PGSQL_MASTER/postgresql.conf
echo "wal_keep_segments = 10" >> $PGSQL_MASTER/postgresql.conf
echo "hot_standby = on" >> $PGSQL_MASTER/postgresql.conf
echo "wal_consistency_checking = 'all'" >> $PGSQL_MASTER/postgresql.conf
echo "archive_mode = on" >> $PGSQL_MASTER/postgresql.conf
echo "archive_command = 'cp %p /tmp/archive_dir/%f'" >> $PGSQL_MASTER/postgresql.conf
echo "wal_log_hints=on" >> $PGSQL_MASTER/postgresql.conf
#echo "wal_debug = on" >> $PGSQL_MASTER/postgresql.conf

#Setup replication settings
echo "local   replication     $USER                               trust" >> $PGSQL_MASTER/pg_hba.conf
echo "host    replication     $USER       127.0.0.1/32            trust" >> $PGSQL_MASTER/pg_hba.conf
echo "host    replication     $USER       ::1/128                 trust" >> $PGSQL_MASTER/pg_hba.conf

#Start Master
export PGPORT=5432
echo "Starting Master.."
$PGSQL_BIN/pg_ctl -D $PGSQL_MASTER -c -w -l master_logfile start

#Perform Backup in the Standy Server
$PGSQL_BIN/pg_basebackup -D $PGSQL_STANDBY
cp $PGSQL_DIR/share/recovery.conf.sample $PGSQL_STANDBY/recovery.conf
echo "standby_mode = on" >> $PGSQL_STANDBY/recovery.conf
echo "primary_conninfo = 'host=localhost port=5432'" >> $PGSQL_STANDBY/recovery.conf
echo "restore_command = 'cp /tmp/archive_dir/%f %p'" >> $PGSQL_STANDBY/recovery.conf
echo "trigger_file = '/tmp/failover.log'" >> $PGSQL_STANDBY/recovery.conf

#Start STANDBY
export PGPORT=5433
echo "Starting Slave.."
$PGSQL_BIN/pg_ctl -D $PGSQL_STANDBY -c -w -l slave_logfile start

#Do some WAL-logging
$PGSQL_BIN/psql -p 5432 -c "CREATE TABLE t1(a int);" postgres
$PGSQL_BIN/psql -p 5432 -c "INSERT INTO t1 SELECT * FROM generate_series(1,10000);" postgres

#Promote standby
touch /tmp/failover.log

sleep 10

#Stop master
export PGPORT=5432
echo "Stoping Master.."
$PGSQL_BIN/pg_ctl -D $PGSQL_MASTER -c -w -l master_logfile stop

echo "Creating large file"
dd if=/dev/zero of=$PGSQL_STANDBY/large.file bs=1024 count=4000000
$PGSQL_BIN/psql -p 5433 -c "CREATE TABLE t2(a int);" postgres
$PGSQL_BIN/psql -p 5433 -c "INSERT INTO t2 SELECT * FROM generate_series(1,10000);" postgres
