#!/bin/bash

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

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

TYPE=primary

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

 while getopts ':psdvh' 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

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

if [[ "$TYPE" == "primary" ]]; then
    CLUSTER_HOST=$PRIMARY_HOST
fi
if [[ "$TYPE" == "standby" ]]; then
    CLUSTER_HOST=$STANDBY_HOST
fi

HTTPD_CONF=/etc/httpd/conf/httpd.conf

# Backup httpd.conf
if [[ ! -f $HTTPD_CONF'.orig' ]]; then
    cp $HTTPD_CONF $HTTPD_CONF'.orig'
else
    # Restore orig
    cp $HTTPD_CONF'.orig' $HTTPD_CONF
fi

# Install nessasary modules
cp modules/mod_* /etc/httpd/modules/
# Install mod_cluster config writed iSergio
cp conf.d/mod_cluster.conf /etc/httpd/conf.d/

# Don't use proxy_balancer, they conflict with mod_cluster_proxy
sed -i '/^LoadModule proxy_balancer_module/s/^/#/' $HTTPD_CONF
# Remove default access to root directory written by vniins
sed -i '/<Directory \/>/,/<\/Directory>/d' $HTTPD_CONF
# Set default encoding to UTF8
sed -i 's/AddDefaultCharset KOI8-R/AddDefaultCharset UTF-8/g' $HTTPD_CONF

# Configure listen ip address
echo -n "Please, enter a ip address of this server(Default: $CLUSTER_HOST): "
read _CLUSTER_HOST
if [[ ! -z $_CLUSTER_HOST ]]; then
    CLUSTER_HOST=$_CLUSTER_HOST
fi
sed -i 's/__CLUSTER_HOST__/'$CLUSTER_HOST'/g' /etc/httpd/conf.d/mod_cluster.conf

# Configure access ip's
echo -n "Please, enter allowed access subnet(Default: $CLUSTER_SUBNET): "
read _CLUSTER_SUBNET
if [[ ! -z $_CLUSTER_SUBNET ]]; then
    CLUSTER_SUBNET=$_CLUSTER_SUBNET
fi
sed -i 's/__CLUSTER_SUBNET__/'$CLUSTER_SUBNET'/g' /etc/httpd/conf.d/mod_cluster.conf

# Turn on auto start of httpd service
chkconfig httpd on
# Restart httpd service
service httpd restart > /dev/null 2>&1
STATUS=$?

align_left "$DOTSTRING" "Configure httpd (ServerGOD)"
if [[ $STATUS == 0 ]]; then
    echo $DONE
else
    echo $FAIL
fi
