#!/bin/bash

PG_PRIMARY_PORT=5432
PG_STANDBY_PORT=5433

# Cleanup anything left over from previous runs.
for d in pgprimary pgstandby; do
    if test -d $d; then
		pg_ctl stop -D $d;
		rm -rf $d
	fi
	rm -f $d.log
done
rm -rf wal_archive

# Echo commands from this point onward and exit on failure.
set -ex

# Create empty WAL archive.
mkdir wal_archive

# Initialize and start primary.
# enable archiving
initdb -D pgprimary
cat >> pgprimary/postgresql.auto.conf <<EOM
port=$PG_PRIMARY_PORT
archive_mode=on
archive_command='cp %p `pwd`/wal_archive/%f'
EOM
pg_ctl start -D pgprimary -l pgprimary.log

# Create archiving only standby
pg_basebackup -D pgstandby -d "port=$PG_PRIMARY_PORT"
cat >> pgstandby/postgresql.auto.conf <<EOM
port=$PG_STANDBY_PORT
restore_command='cp `pwd`/wal_archive/%f %p'
log_min_messages=DEBUG2
EOM
touch pgstandby/recovery.signal

#create table and switch the wal segment
psql -d postgres -c "create table test(a varchar);select pg_switch_wal();"

#write enough record so that it switch the segment at the mid of the last wal record
psql -d postgres -c "insert into test select repeat('a', 1900) from generate_series(1,8535);"
sleep 5

#start standby
#since last wal segemnt is partial it will not be archived and restore so archive recovery will complete
#with aborted record and timeline will switch
pg_ctl -D pgstandby -c -l pgstandby.log -c start

sleep 5
#write data in new timeline
#pgbench -i -s 50 postgres
#psql -d postgres -p 5433 -c "insert into test select repeat('a', 1900) from generate_series(1,10000);"
pgbench -i -s 100 -p 5433 postgres
pgbench -c4 -j4 -T 1000 -M prepared -p 5433 postgres
