#!/bin/bash

# Overwrite the local database with a copy from the primary and
# start the local database in standby mode.

# This script is NOT SUPPORTED by Red Hat Global Support Services.

set -eu

. /usr/libexec/pgsql-replication.sh

if [ "$HOSTNAME" != "$STANDBY_HOST" ]; then
    log INFO "Not on $STANDBY_HOST, exiting"
    exit 0
fi

if service postgresql92-postgresql status >/dev/null; then
    echo "The local database is still running." >&2
    echo "Please verify that $PRIMARY_HOST is" >&2
    echo "the current primary, and then stop the local database." >&2
    exit 1
fi

if ! su -l -c "scl enable postgresql92 -- psql -h $PRIMARY_HOST -U $PGSQL_SQL_USER -w -c 'select 1' vmdb_production" postgres >/dev/null; then
    echo "ERROR: Cannot connect to $PRIMARY_HOST" >&2
    exit 1
fi

echo "Overwriting database files with backup from primary"

# We are starting from scratch, and can remove all WAL files
# that were previously archived.
rm -f $WAL_ARCHIVE_WRITE/*

# Same for the other database files.
rm -rf $PGSQL_HOME/data/*

su -l -c \
  "scl enable postgresql92 -- pg_basebackup -h $PRIMARY_HOST -U replicator -w -D $PGSQL_HOME/data -x" \
  postgres

cat >$PGSQL_HOME/data/recovery.conf <<EOF
standby_mode = 'on'
primary_conninfo = 'host=$PRIMARY_HOST user=replicator'
restore_command = 'cp $WAL_ARCHIVE_READ/%f "%p"'
recovery_target_timeline = 'latest'
EOF

chown postgres:postgres $PGSQL_HOME/data/recovery.conf

if iptables -L -n | grep -q 5432; then
    echo "Closing port 5432"
    iptables_close
fi

echo "Starting and enabling database"
service postgresql92-postgresql start
chkconfig postgresql92-postgresql on
