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

TYPE=primary

usage="$(basename "$0") [-h] [-p|s] [-a|b] [-d] -- Script configure pgpool-II
    where:
        -h  show this help text and exit
        -p  configure PostgreSQL as primary
        -s  configure PostgreSQL as standby
"
while getopts ':psvhabd' option; do
    case "$option" in
        p) TYPE=primary
            ;;
        s) TYPE=standby
            ;;
        h) echo "$usage"
            exit
            ;;
        \?) printf "illegal option: -%s\n" "$OPTARG" >&2
            echo "$usage" >&2
            exit 1
            ;;
    esac
done

/etc/init.d/pgpool stop

sed -i "s/PGPORT=5432/PGPORT=5433/g" /etc/sysconfig/pgsql/postgresql
sed -i '/^DEFAULT_DB_ENCODING/s/^/#/' /etc/sysconfig/pgsql/postgresql
sed -i '/^DEFAULT_DB_LOCALE/s/^/#/' /etc/sysconfig/pgsql/postgresql

if ! grep -Fq "DEFAULT_DB_ENCODING=UTF8" /etc/sysconfig/pgsql/postgresql; then
    echo "DEFAULT_DB_ENCODING=UTF8" >> /etc/sysconfig/pgsql/postgresql
fi
if ! grep -Fq "DEFAULT_DB_LOCALE=ru_RU.UTF8" /etc/sysconfig/pgsql/postgresql; then
    echo "DEFAULT_DB_LOCALE=ru_RU.UTF8" >> /etc/sysconfig/pgsql/postgresql
fi

service postgresql initdb

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

cp -rf tsearch_data/* /usr/share/pgsql/tsearch_data/

if [[ "$TYPE" == "primary" ]]; then
    pg_replication -c
fi
