#!env bash

set -e
#set -x
# show used binaries
type pg_ctl
type pg_basebackup
type initdb
type pgbench

export PGHOST=/tmp/
export PGUSER=postgres

#cleanup
rm -rf /tmp/pgbt-master
rm -rf /tmp/pgbt-standby
rm -rf /tmp/pgbt-standby-standby

# create primary data directory
initdb -U postgres /tmp/pgbt-master > /dev/null
mkdir /tmp/pgbt-master/archive

cat > /tmp/pgbt-master/pg_hba.conf <<EOF
local   all             all                                     trust
local   replication     all                                trust
EOF

options="-c wal_level=hot_standby -c max_wal_senders=10 -c wal_keep_segments=10 -c archive_mode=on -c archive_command='cp %p archive/%f' -c logging_collector=on -c log_filename=postgresql.log -c log_error_verbosity=verbose -c log_min_messages=debug3"
pg_ctl -w -D /tmp/pgbt-master -o "${options} -c port=5431" --log /tmp/pgbt-master/startup.log start
trap "pg_ctl stop -w -D /tmp/pgbt-master" INT QUIT TERM EXIT

echo "plain basebackup without xlog"
pg_basebackup -h /tmp -p 5431 -D /tmp/pgbt-standby
rm -rf /tmp/pgbt-standby

echo "basebackup in fetch mode"
pg_basebackup -h /tmp -p 5431 -D /tmp/pgbt-standby -X fetch

pg_ctl -w -D /tmp/pgbt-standby -o "${options} -c port=5432" --log /tmp/pgbt-master/startup.log start
pg_ctl -w -D /tmp/pgbt-standby stop

rm -rf /tmp/pgbt-standby

echo "basebackup in stream mode"
pg_basebackup -h /tmp -p 5431 -D /tmp/pgbt-standby -X stream

pg_ctl -w -D /tmp/pgbt-standby -o "${options} -c port=5432"  --log /tmp/pgbt-standby/startup.log start
pg_ctl -w -D /tmp/pgbt-standby stop

rm -rf /tmp/pgbt-standby
