#!/bin/bash

# Take a backup of the database and stop it. This is the first step
# in making QDC the primary again after LVDC has been running 
# as primary.

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

set -eu

. /usr/libexec/pgsql-replication.sh

rm -rf $BACKUP_DIR
mkdir $BACKUP_DIR
chown postgres:postgres $BACKUP_DIR

# Close all current transactions and prevent new connections from coming in.
# Otherwise, some data would be missing from the backup that we are going to
# copy to QDC.
if iptables -L -n | grep -q 5432; then
  echo "Blocking incoming connections on port 5432"
  iptables_close
fi

echo "Restarting PostgreSQL to close open transactions"
service postgresql92-postgresql restart

echo "Creating database backup"
su -l -c \
  "scl enable postgresql92 -- pg_basebackup -w -D $BACKUP_DIR -x" \
  postgres

echo "Shutting down and disabling database"
service postgresql92-postgresql stop
chkconfig postgresql92-postgresql off

cd /tmp/pgbackup
tar cfz /tmp/pgbackup.tar.gz .
cd ..
rm -rf /tmp/pgbackup

echo "Copying database to ${PGSQL_SSH_USER}@${PRIMARY_HOST}"
scp /tmp/pgbackup.tar.gz ${PGSQL_SSH_USER}@${PRIMARY_HOST}:/tmp
rm /tmp/pgbackup.tar.gz
echo "Now, run pgsql-primary-initialize on $PRIMARY_HOST"
