#!/usr/bin/env bash
# ========================================== #
# install  phpzookeeper on host machine      #
# Version: for CentOS 6.x                    #
# ========================================== #

PHPVersion=php-5.5.18

zookeeperSourceUrl="http://47.52.95.108/confsys/php-zookeeper-0.2.2.tar.gz"
re2cSourceUrl="http://47.52.95.108/confsys/re2c-0.13.5.tar.gz"

Common_tools="http://47.52.95.108/tools/common_tools.sh"



if [[ -d /usr/local/php-fpm  ]];then
    PHPDir=/usr/local/php-fpm
else
    PHPDir=/usr/local/php
fi


_SYS_CPU_NUMS_=$(cat /proc/cpuinfo | grep -c "model name")
# Check if user is root
if [ $(id -u) != "0" ]; then
    echo "Error: You must be root to run this script, please use root to run";
    exit 1
fi

if [ ! -f 'tools/common_tools.sh' ] ;then
    wget -P "tools" ${Common_tools}
    if [ ! -s 'tools/common_tools.sh' ];then
        exit 1;
    fi
    chmod +x tools/common_tools.sh
fi

if [  -s 'tools/common_tools.sh' ];then
    . tools/common_tools.sh
fi

Install_RE2C(){
    if [[ "$(whereis re2c)" = "re2c:" ]] || [[ "$(whereis re2c)" = "" ]];then
        cd /usr/local/src
        if [[ ! -f re2c-0.13.5.tar.gz ]];then
            wget -c -P /usr/local/src ${re2cSourceUrl}
        fi
        [[ -d re2c-0.13.5 ]] && rm -rf re2c-0.13.5 2>&1 >/dev/null
        tar -xzf re2c-0.13.5.tar.gz
        cd re2c-0.13.5
        ./configure && make -j ${_SYS_CPU_NUMS_} && make install
    fi
}

Install_PHP_EXT_Zookeeper(){
    [[ ! -d ${PHPDir} ]] && Echo_Red "[-] ${PHPDir} does not exist... " && exit 1
    if [[ "$(ls -A ${PHPDir}/lib/php/extensions/no-debug-non-zts-20121212 |grep zookeeper)" = "" ]];then
        Echo_Blue "[+] Installing PHP_EXT zookeeper ..."
        Install_RE2C
        cd /usr/local/src
        if [[ ! -f php-zookeeper-0.2.2.tar.gz ]];then
            wget -c -P /usr/local/src ${zookeeperSourceUrl}
        fi
        tar -xzf php-zookeeper-0.2.2.tar.gz
        cd php-zookeeper-0.2.2
        ${PHPDir}/bin/phpize
        ./configure --with-php-config=${PHPDir}/bin/php-config --with-libzookeeper-dir=/usr/local/zookeeper
        make -j ${_SYS_CPU_NUMS_} && make install
        if [[ "$(cat ${PHPDir}/etc/php.ini |grep zookeeper.so)" = "" ]];then
            sed -i '$!N;/^extension=/{/\nextension=/!a\
extension="zookeeper.so"
};P;D' ${PHPDir}/etc/php.ini
        else
            sed -i 'zookeeper.so/ s@;@@g' ${PHPDir}/etc/php.ini 2>&1 >/dev/null
            #            sed -i 's@^;extension="zookeeper.so"@extension="zookeeper.so"@g' ${PHPDir}/etc/php.ini 2>&1 >/dev/null
        fi
#        service php-fpm restart
    else
        Echo_Blue "[+] PHP_EXT zookeeper intalled already ..."
    fi
}

Install_PHP_EXT_Zookeeper

