#!/bin/bash

# Using a backup that LVDC has copied here, make this server 
# the primary again.

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

set -eu

. /usr/libexec/pgsql-replication.sh

if ! [ -e /tmp/pgbackup.tar.gz ]; then
    echo "ERROR: Cannot find database backup /tmp/pgbackup.tar.gz"
    echo "       Run pgsql-standby-release on $STANDBY_HOST first"
    exit 1
fi

if su -l -c "scl enable postgresql92 -- psql -h $STANDBY_HOST -U $PGSQL_SQL_USER -w -c 'select 1' vmdb_production" postgres >&/dev/null; then
  echo "ERROR: $STANDBY_HOST is still running, not starting local database"
  exit 1
fi

if service postgresql92-postgresql status >/dev/null; then
  echo "Stopping database"
  service postgresql92-postgresql stop
fi

echo "Overwriting database files with backup from standby"

# 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/*

cd $PGSQL_HOME/data
tar xfz /tmp/pgbackup.tar.gz

echo "Starting database"
service postgresql92-postgresql start
