#!/bin/bash

rm -rf /tmp/pgdata{1,2} /tmp/archive{1,2}

mkdir -p /tmp/archive{1,2}

initdb -k /tmp/pgdata1
cat <<EOF >>/tmp/pgdata1/postgresql.auto.conf
listen_addresses = 'localhost'
port = '9967'
archive_mode = 'on'
archive_command = 'cp %p /tmp/archive1/%f'
restore_command = 'cp /tmp/archive1/%f %p'
EOF

pg_ctl -l 1.log -D /tmp/pgdata1 start

pg_basebackup -h localhost -p 9967 -R -Fp -Xs -P -D /tmp/pgdata2

cat <<EOF >>/tmp/pgdata2/postgresql.auto.conf
port = '9968'
archive_command = 'cp %p /tmp/archive2/%f'
restore_command = 'cp /tmp/archive2/%f %p'
EOF

pg_ctl -l 2.log -D /tmp/pgdata2 start

psql postgres -p 9967 -xc 'SELECT * FROM pg_stat_replication'

pgbench -i -s 10 -h localhost -p 9967 postgres

pg_ctl -l 2.log -D /tmp/pgdata2 stop
pg_ctl -l 1.log -D /tmp/pgdata1 stop
pg_ctl -l 1.log -D /tmp/pgdata1 start
pg_ctl -l 2.log -D /tmp/pgdata2 start

psql postgres -p 9967 -xc 'SELECT * FROM pg_stat_replication'
