#!/bin/bash

# Terminate configure if no PostgreSQL installed in system
array=($(rpmquery -a | grep postgresql))
if [[ ${#array[@]} == 0 ]]; then
    echo "PostgreSQL not installed!"
    exit 0
fi

. ../contrib/functions.sh
. ../contrib/config

read -r -p "Configure PostgreSQL stream replication. Continue ? [y/N]" choice
if ! [[ $choice =~ ^([yY][eE][sS]]|[yY])$ ]]; then
    exit 0
fi

/etc/init.d/pgpool stop

cp bin/pg_* /usr/local/bin/

# Configure listen ip address
echo -n "Please, enter a ip address of PRIMARY PostgreSQL server(Default: $PGSQL_PRIMARY_HOST): "
read _PGSQL_PRIMARY_HOST
echo -n "Please, enter a ip address of PRIMARY PgPool server(Default: $PGPOOL_PRIMARY_HOST): "
read _PGPOOL_PRIMARY_HOST
echo -n "Please, enter a ip address of STANDBY PostgreSQL server(Default: $PGSQL_STANDBY_HOST): "
read _PGSQL_STANDBY_HOST
echo -n "Please, enter a ip address of STANDBY PgPool server(Default: $PGPOOL_STANDBY_HOST): "
read _PGPOOL_STANDBY_HOST

if [[ ! -z $_PGSQL_PRIMARY_HOST ]]; then
    PGSQL_PRIMARY_HOST=$_PGSQL_PRIMARY_HOST
fi
if [[ ! -z $_PGPOOL_PRIMARY_HOST ]]; then
    PGPOOL_PRIMARY_HOST=$_PGPOOL_PRIMARY_HOST
fi
if [[ ! -z $_PGSQL_STANDBY_HOST ]]; then
    PGSQL_STANDBY_HOST=$_PGSQL_STANDBY_HOST
fi
if [[ ! -z $_PGPOOL_STANDBY_HOST ]]; then
    PGPOOL_STANDBY_HOST=$_PGPOOL_STANDBY_HOST
fi

sed -i 's/__PGSQL_PRIMARY_HOST__/'$PGSQL_PRIMARY_HOST'/g' /usr/local/bin/pg_replication
sed -i 's/__PGSQL_STANDBY_HOST__/'$PGSQL_STANDBY_HOST'/g' /usr/local/bin/pg_replication
sed -i 's/__PGPOOL_PRIMARY_HOST__/'$PGPOOL_PRIMARY_HOST'/g' /usr/local/bin/pg_replication
sed -i 's/__PGPOOL_STANDBY_HOST__/'$PGPOOL_STANDBY_HOST'/g' /usr/local/bin/pg_replication

pg_replication -c
