#!/bin/bash

# Check if we can connect to the database on the second node.
# It's either up in standby mode, up in primary mode, or down.
#
# We only start the local database if the secondary node is not in
# primary mode.
#
# This is made easier by the fact that the second node blocks
# connections to port 5432 if it is in standby mode.

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

set -eu

. /usr/libexec/pgsql-replication.sh

exec >>/var/log/pgsql-primary-check-start.log 2>&1

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

if [ ! -e /var/lib/pgsql/.pgpass ]; then
    log ERROR "Please create /var/lib/pgsql/.pgpass"
    exit 1
fi

if /sbin/service postgresql92-postgresql status >/dev/null; then
    log WARNING "PostgreSQL is already running locally, exiting"
    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
    log INFO "$STANDBY_HOST is running as primary, not starting local database"
else
    log INFO "Cannot connect to $STANDBY_HOST, starting local database"

    /sbin/service postgresql92-postgresql start
fi

