#!/bin/bash

# Cleanup the data.
rm -rf /tmp/{pgdata,arch,log}{1,2}

# Create the archive directories.
mkdir -p /tmp/arch{1,2}

# Initialize the primary node.
initdb -k -D /tmp/pgdata1 -U jerry
cat <<EOF >>/tmp/pgdata1/postgresql.auto.conf
port = '9967'
archive_mode = 'always'
archive_command = 'test ! -f /tmp/arch1/%f && cp %p /tmp/arch1/%f'
restore_command = 'cp /tmp/arch1/%f %p'

logging_collector = 'on'
log_destination = 'csvlog'
log_filename = 'postgresql-%d.log'
log_directory = '/tmp/log1'
EOF

# Startup the primary node.
pg_ctl -l 1.log -D /tmp/pgdata1 start

# Create the standby node.
pg_basebackup -U jerry -h localhost -p 9967 -R -Fp -Xs -P -D /tmp/pgdata2
cat <<EOF >>/tmp/pgdata2/postgresql.auto.conf
port = '9968'
archive_mode = 'always'
archive_command = 'test ! -f /tmp/arch2/%f && cp %p /tmp/arch2/%f'
restore_command = 'cp /tmp/arch2/%f %p'

logging_collector = 'on'
log_destination = 'csvlog'
log_filename = 'postgresql-%d.log'
log_directory = '/tmp/log2'
EOF

# Startup the standby node.
pg_ctl -l 2.log -D /tmp/pgdata2 start

# Check the replication.
psql -U jerry -p 9967 postgres -xc 'select * from pg_stat_replication'

# Stop the primary and then promote the standby to new primary.
pg_ctl -l 1.log -D /tmp/pgdata1 stop
pg_ctl -l 2.log -D /tmp/pgdata2 promote

# Re-join the old primary as new standby.
cat <<EOF >>/tmp/pgdata1/postgresql.auto.conf
primary_conninfo = 'user=jerry host=localhost port=9968'
EOF
touch /tmp/pgdata1/standby.signal
pg_ctl -l 1.log -D /tmp/pgdata1 start

# Check the replication
psql -U jerry -p 9968 postgres -xc 'select * from pg_stat_replication'

# Check the archiver process status.
ps -ef | grep archiver

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