#!/bin/bash

# Default server hosts
PRIMARY_HOST=172.16.0.104
STANDBY_HOST=172.16.0.204

TPYE=primary

usage="$(basename "$0") [-h] [-p] [-s] -- Script configure pgpool-II
 where:
     -h  show this help text and exit
     -p  configure pgpool as primary
     -s  configure pgpool as standby"

while getopts ':psdvh' option; do
    case "$option" in
        p) TYPE=primary
            ;;
        s) TYPE=standby
            ;;
        v) VERBOSE=true
            ;;
        d) DEPLOY=true
            ;;
        h) echo "$usage"
            exit
            ;;
        \?) printf "illegal option: -%s\n" "$OPTARG" >&2
            echo "$usage" >&2
            exit 1
           ;;
   esac
done

# pgpool dir
PGPOOL_DIR=/etc/pgpool-II
PGPOOL_CONFIG=$PGPOOL_DIR/pgpool.conf

cp -rf pgpool-II/pgpool-$TYPE.conf $PGPOOL_CONFIG
cp -rf init.d/pgpool /etc/init.d/pgpool
cp -rf sysconfig/pgpool /etc/sysconfig/pgpool

echo "postgres:"`pg_md5 postgres` >> $PGPOOL_DIR/pcp.conf

chmod 4755 /sbin/ifconfig
chmod 4755 /usr/sbin/arping

touch /etc/pgpool-II/pool_passwd
chown postgres /etc/pgpool-II/pool_passwd

mkdir /var/log/pgpool
chown postgres /var/log/pgpool

# Change default PostgreSQL port to 5433
sed -i "s/PGPORT=5432/PGPORT=5433/g" /etc/sysconfig/pgsql/postgresql
/etc/init.d/postgresql restart

chkconfig pgpool on

# Add check status of nodes every minute into cron
echo '* * * * * root /usr/local/bin/pg_auto_attach_node' >> /etc/crontab
/etc/init.d/crond restart
