#! /bin/sh
echo "#### initial settings ####"
PGPATH=`pwd`"/bin"
PATH=$PGPATH:$PATH
PGDATA0="Master"
PGDATA1="Standby"
PGARC="arc"
mkdir $PGARC
PGPORT0=65432
PGPORT1=65433
unset PGPORT
unset PGDATA
echo "Postgresql is \"`which postgres`\""
killall -9 postgres
rm -rf $PGDATA0 $PGDATA1 $PGARC/*
initdb $PGDATA0
cat >> $PGDATA0/postgresql.conf <<EOF
port=$PGPORT0
wal_level = hot_standby
checkpoint_segments = 3
checkpoint_timeout = 1h
archive_mode = on
archive_command = 'cp %p ../$PGARC/%f'
max_wal_senders = 3
hot_standby = on
log_min_messages = debug2
log_line_prefix = '[Master] %t '
log_min_duration_statement = 20s
log_checkpoints = on
log_error_verbosity = verbose
log_lock_waits = on
track_activities = on
track_counts = on
track_functions = all
EOF
cat >> $PGDATA0/pg_hba.conf <<EOF
local  replication      all			trust
host   replication	all	127.0.0.1/32	trust
host   replication      all     ::1/128		trust
EOF
echo "#### Startup master ####"
pg_ctl -D $PGDATA0 -w  start
createuser postgres -s -p $PGPORT0

echo "#### basebackup ####"
pg_basebackup -p $PGPORT0 -F p -X s -D $PGDATA1
cat >> $PGDATA1/recovery.conf <<EOF
standby_mode = 'yes'
recovery_target_timeline='latest'
primary_conninfo='host=localhost port=$PGPORT0'
restore_command='cp ../$PGARC/%f %p'
EOF

cat >> $PGDATA1/postgresql.conf <<EOF
port=$PGPORT1
wal_level = hot_standby
checkpoint_segments = 3
checkpoint_timeout = 1h
archive_mode = on
archive_command = 'cp %p ../$PGARC/%f'
max_wal_senders = 3
hot_standby = on
log_min_messages = debug2
log_line_prefix = '[Standby] %t '
log_min_duration_statement = 20s
log_checkpoints = on
log_error_verbosity = verbose
log_lock_waits = on
track_activities = on
track_counts = on
track_functions = all
EOF


echo "#### Startup standby ####"
pg_ctl -D $PGDATA1 start
echo "#### Sleep for 5 seconds ####"
sleep 5

echo "#### Shutdown standby ####"
pg_ctl -D $PGDATA1 -w stop -m f
ls $PGDATA1/

echo "#### Shutdown master in immediate mode ####"
pg_ctl -D $PGDATA0 -w stop -m i

echo "#### Sleep for 5 seconds ####"
sleep 5

cat >> $PGDATA0/recovery.conf <<EOF
standby_mode = 'yes'
recovery_target_timeline='latest'
primary_conninfo='host=localhost port=$PGPORT1'
restore_command='cp ../$PGARC/%f %p'
EOF

echo "#### Starting master as a standby, and next promote####"
pg_ctl -w -D $PGDATA0 start
pg_ctl -w -D $PGDATA0 promote

echo "#### Sleep for 5 seconds ####"
sleep 5
pgbench -i -s 50 -U postgres -p $PGPORT0


echo "#### Shutdown master in immediate mode ####"
pg_ctl -D $PGDATA0 -w stop -m i

cat >> $PGDATA0/recovery.conf <<EOF
standby_mode = 'yes'
recovery_target_timeline='latest'
primary_conninfo='host=localhost port=$PGPORT1'
restore_command='cp ../$PGARC/%f %p'
EOF

echo "#### Starting master as a standby, and next promote####"
pg_ctl -w -D $PGDATA0 start
pg_ctl -w -D $PGDATA0 promote

echo "#### Sleep for 5 seconds ####"
sleep 5

echo "#### Was latest .history file archived ??? ####"
sleep 2
echo "#### Starting standby ####"
pg_ctl -w -D $PGDATA1 start

