#!/bin/bash

PG_PRIMARY_PORT=5432
PG_STANDBY_PORT=5433
PG_CASCADE_PORT=5434

# Cleanup anything left over from previous runs.
for d in pgprimary pgstandby pgcascade; do
    if test -d $d; then
		pg_ctl stop -D $d;
		rm -rf $d
	fi
	rm -f $d.log
done
rm -rf wal_archive
rm -rf wal_archive1
# Echo commands from this point onward and exit on failure.
set -ex

# Create empty WAL archive.
mkdir wal_archive
mkdir wal_archive1

# 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'
archive_command='cp %p `pwd`/wal_archive1/%f'
log_min_messages=DEBUG2
EOM
touch pgstandby/recovery.signal

# Generate a lot of WAL so that standby takes time to come out of archive recovery
psql -d postgres -c "create table test1(a varchar);"
psql -d postgres -c "insert into test1 select repeat('a', 1900) from generate_series(1,100000);"

#start the standby
pg_ctl -D pgstandby -c -l pgstandby.log -c start

#start cascade standby
pg_basebackup -D pgcascade -R -d "port=$PG_STANDBY_PORT"
cat >> pgcascade/postgresql.auto.conf <<EOM
port=$PG_CASCADE_PORT
restore_command='cp `pwd`/wal_archive1/%f %p'
EOM
pg_ctl -D pgcascade -c -l pgcascade.log -c start


#create table and switch the wal segment
#this will create 0 filled gap in WAL file 00000002000000000000000F on pgstandby which will be sent to pgcascade
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 2

pgbench -i -s 1 -p 5433 postgres
