#!/bin/bash

set -e

mkdir walarchive

bin/initdb -D data-master -N

cat >> data-master/postgresql.conf <<EOF
wal_level = hot_standby
archive_mode = on
archive_command = 'test ! -f $PWD/walarchive/%f && cp %p $PWD/walarchive/%f'
log_line_prefix='%m '
log_checkpoints=on
synchronous_commit=off
checkpoint_segments=10
full_page_writes=off
EOF

bin/pg_ctl -w -D data-master start
bin/pg_ctl -w -D data-master stop
cp -a data-master data-backup

cat >> data-backup/recovery.conf <<EOF
restore_command='cp $PWD/walarchive/%f %p'
EOF
cp -a data-backup data-standby

bin/pg_ctl -w -D data-master start

#### Generate WAL

BEGINWAL=`bin/psql  postgres -c "select pg_current_xlog_insert_location()" -t -A`

bin/pgbench  -i -s 5 postgres
bin/pgbench -M prepared -t1000000 -P10 -c4 -j4 postgres

# Print the amount of WAL generated
bin/psql postgres -c "select pg_switch_xlog()"
bin/psql postgres -c "select pg_current_xlog_insert_location() - '$BEGINWAL'" 

### Done! Stop master and start archive recovery from backup

bin/pg_ctl -w -D data-master stop


bin/pg_ctl -w -D data-standby start
