#!/bin/sh

### Environment
INSTALL_TARGET="auto"
if [ -n "$1" ]; then
    INSTALL_TARGET=$1
else
    INSTALL_TARGET="auto"
fi

WHATAP_NAME="whatap"
WHATAP_HOME=/usr/${WHATAP_NAME}/php
WHATAP_MODULES="$WHATAP_HOME/modules"
WHATAP_ACCESS_KEY=""
WHATAP_SERVER_HOST=""

# Linux (Redhat , Ubuntu)
WHATAP_SERVICE_FILE="${WHATAP_HOME}/${WHATAP_NAME}-php"
# FreeBSD
# WHATAP_SERVICE_FILE="/etc/rc.d/${WHATAP_NAME}_php"

WHATAP_SERVICE_NAME="${WHATAP_NAME}-php"
WHATAP_MODULE_FILE="${WHATAP_NAME}.so"
WHATAP_PACKAGE_NAME="${WHATAP_NAME}-php"
WHATAP_BUILD_ARCH="x64"
WHATAP_INI_TEMPLATE="$WHATAP_HOME/template.ini"
WHATAP_LOG_DIR="$WHATAP_HOME/logs"

########## Packet Remove script
## Ubuntu
#WHATAP_REMOVE_PACKAGE="apt-get purge ${WHATAP_PACKAGE_NAME}"
# Redhat
WHATAP_REMOVE_PACKAGE="rpm -e ${WHATAP_PACKAGE_NAME}"
# FreeBSD
#WHATAP_REMOVE_PACKAGE="pkg delete ${WHATAP_PACKAGE_NAME}"

WHATAP_WEB=""
WHATAP_WEB_PROCESS=""
WEB_ZTS=""

PHP_API=""
PHP_EXTENSION_DIR=""
PHP_INI_DIR=""
PHP_CONF_FILE=""

PHP_ZTS=""
PHP_ZTS_EXTENSION_DIR=""
PHP_ZTS_INI_DIR=""

PHP_BIN=""

PATH_APACHE=
IS_APACHE=false
IS_APACHE2=false

PATH_APACHECTL=
IS_APACHECTL=false

IS_NGINX=false

PATH_PHP_FPM=
IS_PHP_FPM=false
IS_PHP5_FPM=false

PATH_PHP=
IS_PHP=false
IS_PHP5=false

PATH_PHP_ZTS=
IS_PHP_ZTS=false
IS_ZTS_PHP=false


service_path=`which service`


### Log Directory
if [ ! -d "$WHATAP_LOG_DIR" ]; then
    mkdir "$WHATAP_LOG_DIR"
fi

#Set up the logging environment
#
#datetemp=`date +%Y%m%d-%H%M%S 2> /dev/null`
datetemp=`date +%Y%m%d 2> /dev/null`
WHATAP_LOG_FILE="$WHATAP_LOG_DIR/${WHATAP_NAME}-install-$datetemp.log"

# Create the log file
echo "WHATAP PHP-APM Agent Install Log dated: $now" > $WHATAP_LOG_FILE

# Log function
log() {
    echo "$1" >> $WHATAP_LOG_FILE
    if $2; then
        echo "$1"
    fi
}

############# Function
help(){
        echo "Usage: install.sh"
        echo "  install.sh [ commands manual|remove ] "
        echo "  install.sh -l <access(license) key> -s <server> -v <php version> -i <php config file> -p <process_name> [-z ] "
        echo "  install.sh -l <access(license) key> -s <server> -e <php command> -p <process_name> [-z ] "
        echo " "
        echo "Commands"
        echo "  auto(default)         Auto scan web server and php environment "
        echo "  manual                User input web server and php environment "
        echo "  remove                Remove php extension and service(${WHATAP_PACKAGE_NAME})"
        echo " "
        echo "Options"
        echo "  -v <php version>      PHP version ex) 5.2, 5.3, 5.4, 5.5, 5.6, 7.0, 7.1, 7.2, 7.3, 7.4, 8.0, 8.1, 8.2, 8.3, 8.4 "
        echo "                        -v 5.3, --php-version 5.3 "
        echo "  -i <php config file>  PHP config file "
        echo "                        -i /etc/php.ini, --php-ini /etc/php.ini "
        echo "  -e <php cli>          PHP CLI(command line interface) "
        echo "                        -e /usr/bin/php , --php-exe: /usr/bin/php-fpm "
        echo "  -p <process name>     Web server or PHP-FPM process name. for get used memory"
        echo "                        -p httpd, -p httpd.worker, -process-name: php-fpm "
        echo "  -l <access(license) key>          Access(License) key"
        echo "                        -l xxxxxxxxxx, --accesskey: xxxxxxxxxx, --license: xxxxxxxxxx "
        echo "  -s <server>           Whatap Server Host "
        echo "                        -s xx.xx.xx.xx/yy.yy.yy.yy, -server xxx.xxx.xxx.xxx "
        echo "  -z                    PHP thread safe "
        echo "                        -z , --php-zts "
}

make_init() {
     log "make_init skipped"
#    # Linux (Redhat , Ubuntu)
#    start_script="$service_path ${WHATAP_SERVICE_NAME} start"
#    if [ -f /usr/sbin/update-rc.d ] ; then
#        update-rc.d  ${WHATAP_SERVICE_NAME} defaults 2>&1 | logger -t "${WHATAP_NAME}"
#    elif [ -f /sbin/chkconfig ] ; then
#        #centos
#        chkconfig  --add ${WHATAP_SERVICE_NAME} 2>&1 | logger -t "${WHATAP_NAME}"
#        chkconfig  ${WHATAP_SERVICE_NAME} on 2>&1 | logger -t "${WHATAP_NAME}"
#    elif [ -n `which systemctl 2> /dev/null` ] ; then
#        systemctl enable ${WHATAP_SERVICE_NAME}
#    elif [[ -z `grep  ${WHATAP_SERVICE_NAME} /etc/rc.local` ]] ; then
#        echo $start_script >> /etc/rc.local 2>&1 | logger -t "${WHATAP_NAME}"
#    else
#        logger -t " ${WHATAP_SERVICE_NAME}" "There is no init script installer."
#    fi

    # FreeBSD
    # tmp=`cat /etc/rc.conf | grep ${WHATAP_SERVICE_NAME}`
    # if [ -n "${tmp}" ]; then
    #     sed -i '' "/${WHATAP_SERVICE_NAME}_php_enable=/c\\
    # ${WHATAP_SERVICE_NAME}_enable=YES" /etc/rc.conf
    # else
    #     echo '${WHATAP_SERVICE_NAME}_enable=YES' >> /etc/rc.conf
    # fi
}

make_remove() {
    ########## Remove Service
    # Linux (Redhat , Ubuntu)
    # if [ -f /usr/sbin/update-rc.d ] ; then
    #     update-rc.d -f ${WHATAP_SERVICE_NAME} remove
    # elif [ -f /sbin/chkconfig ] ; then
    #     chkconfig ${WHATAP_SERVICE_NAME} off
    #     chkconfig --del ${WHATAP_SERVICE_NAME}
    # elif [ -n `which systemctl` ] ; then
    #     systemctl disable ${WHATAP_SERVICE_NAME}
    # fi

    ########## Remove php extension ini, module
    ## Ubuntu php enmod
    #php5dismod=`which php5dismod 2> /dev/null`
    #phpdismod=`which phpdismod 2> /dev/null`

    #if [ -n "$php5dismod" ]; then
    #    php5dismod ${WHATAP_NAME}
    #else
    #    phpdismod ${WHATAP_NAME}
    #fi
    #log "PHP dismod ${WHATAP_NAME}" true

    stop_agent

    # FreeBSD
    #/etc/rc.conf remove whatap_php_enable
    # sed -i '' '/whatap/d' /etc/rc.conf 2> /dev/null

    # Get WHATAP_CONFIG_HOME
    # cat /etc/init.d/whatap-php | grep 'WHATAP_CONFIG_HOME'
    #WHATAP_CONFIG_HOME=/etc/php.d
    tmp=`cat ${WHATAP_SERVICE_FILE} | grep 'WHATAP_CONFIG_HOME'`
    if [ -n "${tmp}" ]; then
        if echo ${tmp} | grep -q "WHATAP_CONFIG_HOME"; then
            PHP_INI_DIR=${tmp#*WHATAP_CONFIG_HOME=}
            log "PHP_INI_DIR=$PHP_INI_DIR" false
        else
            log "Error: PHP_INI_DIR" true
        fi
    else
        log "Error: Not found PHP_INI_DIR" true
    fi
    rm -f "$PHP_INI_DIR/${WHATAP_NAME}.ini"
    log "Remove INI=$PHP_INI_DIR/${WHATAP_NAME}.ini" true


    # Get WHATAP_PHP_BIN
    # cat /etc/init.d/whatap-php | grep 'WHATAP_PHP_BIN'
    #WHATAP_CONFIG_HOME=/etc/php.d
    tmp=`cat ${WHATAP_SERVICE_FILE} | grep 'WHATAP_PHP_BIN'`
    if [ -n "${tmp}" ]; then
        if echo ${tmp} | grep -q "WHATAP_PHP_BIN"; then
            PHP_BIN=${tmp#*WHATAP_PHP_BIN=}
            log "PHP_BIN=$PHP_BIN" false
        else
            log "Error: PHP_BIN" true
        fi
    else
        log "Error: Not found PHP_BIN" true
    fi

    # Get PHP Configureation File
    # php -i | grep 'Loaded Configuration File'
    php_path=$PHP_BIN
    tmp=`$php_path -i | grep 'Loaded Configuration File'`
    if [ -n "${tmp}" ]; then
        if echo ${tmp} | grep -q 'Loaded Configuration File'; then
            tmp=${tmp#*=> }
            tmp=${tmp#*=> }
            PHP_CONF_FILE=${tmp}
            log "PHP CONF FILE=$PHP_CONF_FILE" true
        else
            log "Error: PHP Confing file is none" true
        fi
    else
        log "Error: Not found PHP Config file" true
    fi

    # Remove php.ini
    # TODO remove_php_conf
    # sed -i '/whatap/d' ${PHP_CONF_FILE} 2> /dev/null
    remove_php_conf

    # Get WHATAP_PHP_EXT_HOME
    # cat /etc/init.d/whatap-php | grep 'WHATAP_PHP_EXT_HOME'
    #WHATAP_PHP_EXT_HOME=/usr/lib64/php/modules
    tmp=`cat ${WHATAP_SERVICE_FILE} | grep 'WHATAP_PHP_EXT_HOME'`
    if [ -n "${tmp}" ]; then
        if echo ${tmp} | grep -q 'WHATAP_PHP_EXT_HOME'; then
            PHP_EXTENSION_DIR=${tmp#*WHATAP_PHP_EXT_HOME=}
            log "PHP_EXTENSION_DIR=$PHP_EXTENSION_DIR" false
        else
            log "Error: PHP_EXTENSION_DIR" true
        fi
    else
        log "Error: Not found PHP_EXTENSION_DIR" true
    fi
    rm -f "$PHP_EXTENSION_DIR/${WHATAP_MODULE_FILE}"
    log "Remove Module=$PHP_EXTENSION_DIR/${WHATAP_MODULE_FILE}" true

    #remove shared memory and semaphore
    ipcrm -S 6600 -M 6600 > /dev/null 2>&1
    
    ## Remove Package
    log "" true
    #log "Please Remove Package $WHATAP_REMOVE_PACKAGE" true
    log "Please remove /usr/whatap/php directory " true
}

start_agent() {
    /usr/whatap/php/whatap-php start 
#    if [ -n `which systemctl 2> /dev/null` ] ; then
#        systemctl start ${WHATAP_SERVICE_NAME}
#    el
#        $service_path ${WHATAP_SERVICE_NAME} start    
#    fi
}
stop_agent() {
    /usr/whatap/php/whatap-php stop
#    if [ -n `which systemctl 2> /dev/null` ] ; then
#        systemctl stop ${WHATAP_SERVICE_NAME}
#    el
#        $service_path ${WHATAP_SERVICE_NAME} stop    
#    fi
}
restart_agent() {
    /usr/whatap/php/whatap-php     
#    if [ -n `which systemctl 2> /dev/null` ] ; then
#        systemctl restart ${WHATAP_SERVICE_NAME}
#    el
#        $service_path ${WHATAP_SERVICE_NAME} restart    
#    fi
}

# check process function
check_process(){
    #log "check_process::parameter $1" true
    t=$(ps aux | grep $1)
    #log "check_process::result ${t}" true
    if [ -n "${t}" ]; then
        true
    else
        false
    fi
}

############# Get Env
get_env() {
    tmp=`which httpd 2> /dev/null`
    if [ -n "${tmp}" ]; then
        IS_APACHE=true
        PATH_APACHE=${tmp}
    fi
    tmp=`which apache2 2> /dev/null`
    if [ -n "${tmp}" ]; then
        IS_APACHE2=true
        PATH_APACHE=${tmp}
    fi
    tmp=`which apachectl 2> /dev/null`
    if [ -n "${tmp}" ]; then
        IS_APACHECTL=true
        PATH_APACHECTL=${tmp}
    fi
    tmp=`which nginx 2> /dev/null`
    if [ -n "${tmp}" ]; then
        IS_NGINX=true
    fi
    tmp=`which php-fpm 2> /dev/null`
    if [ -n "${tmp}" ]; then
        IS_PHP_FPM=true
        PATH_PHP_FPM=${tmp}
    fi
    tmp=`which php5-fpm 2> /dev/null`
    if [ -n "${tmp}" ]; then
        IS_PHP5_FPM=true
        PATH_PHP_FPM=${tmp}
    fi
    tmp=`which php 2> /dev/null`
    if [ -n "${tmp}" ]; then
        IS_PHP=true
        PATH_PHP=${tmp}
    fi
    tmp=`which php5 2> /dev/null`
    if [ -n "${tmp}" ]; then
        IS_PHP5=true
        PATH_PHP=${tmp}
    fi
    tmp=`which php-zts 2> /dev/null`
    if [ -n "${tmp}" ]; then
        IS_PHP_ZTS=true
        PATH_PHP_ZTS=${tmp}
    fi
    tmp=`which zts-php 2> /dev/null`
    if [ -n "${tmp}" ]; then
        IS_ZTS_PHP=true
        PATH_PHP_ZTS=${tmp}
    fi

    # DEBUG ##############################
    # IS_APACHE=false
    # IS_APACHE2=false
    # IS_APACHECTL=false
    # IS_PHP_FPM=false
    # IS_PHP5_FPM=false
    # IS_PHP=true
    # IS_PHP5=true
    # IS_PHP_ZTS=false
    # IS_ZTS_PHP=false
    ####################################

    log "a=$IS_APACHE,a2=$IS_APACHE2,ac=$IS_APACHECTL,n=$IS_NGINX,f=$IS_PHP_FPM,f5=$IS_PHP5_FPM,p=$IS_PHP,p5=$IS_PHP5,pz=$IS_PHP_ZTS,zp=$IS_ZTS_PHP" false
    log "a=$PATH_APACHE,ac=$PATH_APACHECTL,f=$PATH_PHP_FPM,p=$PATH_PHP,pz=$PATH_PHP_ZTS" false
}

############# User Input
read_input() {
    #Get Access Key
    read_accesskey
    #Get whatap.server.host
    read_server_host

    # Read Apache
    if $IS_APACHE || $IS_APACHE2 || $IS_APACHECTL; then
        log "Found Apache ${PATH_APACHE}, ${PATH_APACHECTL}" true
    elif $IS_PHP_FPM || $IS_PHP5_FPM; then
        log "Found PHP-Fpm ${PATH_PHP_FPM}" true
    else
        read_apache_fpm
    fi

    # Read PHP
    if $IS_PHP || $IS_PHP5 || $IS_PHP_ZTS || $IS_ZTS_PHP; then
        log "Found PHP nts:${PATH_PHP}, zts:${PATH_PHP_ZTS}" true
    else
        read_php
    fi
}

read_accesskey() {
    #Get Access Key
    log "Enter access key(license key)" true
    read input
    log "Access key=$input" false
    WHATAP_ACCESS_KEY="${WHATAP_NAME}.accesskey=$input"
}

read_server_host() {
    #Get whatap.server.host
    log "Enter WhaTap server IP. ${WHATAP_NAME}.server.host" true
    read input
    log "Server.host=$input" false
    WHATAP_SERVER_HOST="${WHATAP_NAME}.server.host=$input"
}

read_apache_fpm() {
    #Get APache, Fpm which
    log "Enter the full path for the 'apachectl' or 'php-fpm' command, " true 
    log "such as '/usr/sbin/apachectl', '/usr/bin/httpd' or '/usr/sbin/php-fpm' and so on." true
    log "Please pay attention and don't miss the last executed command. " true
    log "Also, please avoid entering multiple commands separated by commas." true
    read input
    MANUAL_WHICH_WEB=$input
    if echo ${MANUAL_WHICH_WEB} | grep -q 'apachectl'; then
        PATH_APACHECTL=$input
        IS_APACHECTL=true
    elif echo ${MANUAL_WHICH_WEB} | grep -q 'http'; then
        PATH_APACHE=$input
        IS_APACHE=true
    elif echo ${MANUAL_WHICH_WEB} | grep -q 'apache'; then
        PATH_APACHE=$input
        IS_APACHE=true
    else
        PATH_PHP_FPM=$input
        IS_PHP_FPM=true
    fi
    log "Manual Input Web=${MANUAL_WHICH_WEB}" false
}

read_php(){
    #Get PHP which
    log "Enter the full path for the 'php' command, " true 
    log "such as '/usr/bin/php', '/usr/bin/zts-php' or '/usr/sbin/php-fpm' and so on." true
    log "Please pay attention and don't miss the last executed command. " true
    log "Also, please avoid entering multiple commands separated by commas." true
	read input
    MANUAL_WHICH_PHP=$input
    PATH_PHP=$input
    IS_PHP=true
    log "Manual Input php=$MANUAL_WHICH_PHP" false
}

read_manual() {
    read_accesskey
    read_server_host
    read_apache_fpm
    ## httpd
    if echo ${MANUAL_WHICH_WEB} | grep -q 'httpd'; then
        IS_APACHE=true
        IS_APACHE2=false
        IS_PHP_FPM=false
        IS_PHP5_FPM=false
        read_php
    elif echo ${MANUAL_WHICH_WEB} | grep -q 'apache2'; then
        IS_APACHE=false
        IS_APACHE2=true
        IS_PHP_FPM=false
        IS_PHP5_FPM=false
        read_php
    elif echo ${MANUAL_WHICH_WEB} | grep -q 'php-fpm'; then
        IS_PHP_FPM=true
        IS_PHP5_FPM=false
        IS_APACHE=false
        IS_APACHE2=false
    elif echo ${MANUAL_WHICH_WEB} | grep -q 'php5-fpm';  then
        IS_PHP_FPM=false
        IS_PHP5_FPM=true
        IS_APACHE=false
        IS_APACHE2=false
    else
        read_php
    fi
}

############# BUILD ARCH
#tmp=$(uname -a)

get_build_arch() {
    tmp=$(uname -m)
    if [ -n "${tmp}" ]; then
        if echo ${tmp} | grep -q '_64'; then
            WHATAP_BUILD_ARCH="x64"
            log "${tmp}, ARCH=${WHATAP_BUILD_ARCH}" true
        elif echo ${tmp} | grep -q 'amd64'; then
            WHATAP_BUILD_ARCH="x64"
            log "${tmp}, ARCH=${WHATAP_BUILD_ARCH}" true
        elif echo ${tmp} | grep -q 'aarch64'; then
            WHATAP_BUILD_ARCH="aarch64"
            log "${tmp}, ARCH=${WHATAP_BUILD_ARCH}" true
        elif echo ${tmp} | grep -q 'arm64'; then
            WHATAP_BUILD_ARCH="aarch64"
            log "${tmp}, ARCH=${WHATAP_BUILD_ARCH}" true
        else
            log "Not support build arch uname ${tmp}" true
        fi
    else
        log "Error: Not found WHATAP_BUILD_ARCH" true
    fi
}

############# Apache Web Server Info
get_apache_info() {
    apache_path=$1
    log "get_apachectl_info ARGS=$apache_path" false
    if [ -n "${apache_path}" ]; then
        log "apache_path=$apache_path" false
        WHATAP_WEB="APHP"

        tmp=`${apache_path} -V | grep SERVER_CONFIG_FILE`
        if [ -n "${tmp}" ]; then
                tmp=`echo $tmp | tr '[A-Z]' '[a-z]'`
            log "get_apachectl_info apache_result=$tmp" false

            ## Get Apache process name
            if echo ${tmp} | grep -q 'server_config_file'; then
                tmp=${tmp#*server_config_file=\"}
                tmp=${tmp%\"}
                HTTPD_ROOT=${tmp}
                log "HTTPD_ROOT=${HTTPD_ROOT}" false

                tmp=`$apache_path -V`
                if echo ${HTTPD_ROOT} | grep -q 'httpd'; then
                    if echo ${tmp} | grep -q 'prefork'; then
                        WEB_ZTS=""
                        WHATAP_WEB_PROCESS="httpd"
                    elif echo ${tmp} | grep -q 'worker'; then
                        WEB_ZTS="_zts"
                        WHATAP_WEB_PROCESS="httpd.worker"
                    else
                        WEB_ZTS="_zts"
                        WHATAP_WEB_PROCESS="httpd.event"
                    fi
                elif echo ${HTTPD_ROOT} | grep -q 'apache2'; then
                    if echo ${tmp} | grep -q 'prefork'; then
                        WEB_ZTS=""
                        WHATAP_WEB_PROCESS="apache2"
                    else
                        WEB_ZTS="_zts"
                        WHATAP_WEB_PROCESS="apache2"
                    fi
                else
                    WEB_ZTS=""
                    WHATAP_WEB_PROCESS="httpd"
                fi
            else
                    log "Error: HTTPD_ROOT is none" false
            fi

            log "WHATAP_WEB=$WHATAP_WEB, WEB_ZTS=$WEB_ZTS, WHATAP_WEB_PROCESS=$WHATAP_WEB_PROCESS" true
        else
            log "Warn: apachectl result is none, Process NZTS, httpd " true
        fi
    else
        log "Error: Not found apachectl PATH, Process NZTS" true
    fi
}
############# PHP-FPM Server Info
#php-fpm -i |  | grep 'Thread'
#Thread Safety => disabled

get_php_fpm_info() {
    if [ -n "$1" ]; then
        tmp==`echo $1 | tr '[A-Z]' '[a-z]'`
        if echo ${tmp} | grep -q 'php-fpm'; then
            WHATAP_WEB_PROCESS="php-fpm"
        elif echo ${tmp} | grep -q 'php5-fpm'; then
            WHATAP_WEB_PROCESS="php5-fpm"
        else
            WHATAP_WEB_PROCESS=${tmp##*/}
        fi
        php_fpm_path=$1
        log "get_php_fpm_info ARGS=$1" false
    else
        ## Ubuntu php5-fpm, 7.0 7.1 php-fpm
        if $IS_PHP_FPM; then
            php_fpm_path=`which php-fpm`
            WHATAP_WEB_PROCESS="php-fpm"
        elif $IS_PHP5_FPM; then
            php_fpm_path=`which php5-fpm`
            WHATAP_WEB_PROCESS="php5-fpm"
        fi
    fi

    if [ -n "${php_fpm_path}" ]; then
        tmp=`$php_fpm_path -i | grep 'Thread' `
        log "get_php_frpm_info::$php_fpm_path" false

        if [ -n "${tmp}" ]; then
            WHATAP_WEB="FPHP"
            if echo ${tmp} | grep -q 'enabled'; then
                WEB_ZTS="_zts"
                log "get_php_frpm_info::WEB_ZTS=$WEB_ZTS" false
            else
                WEB_ZTS=""
                log "get_php_frpm_info::WEB_ZTS=$WEB_ZTS" false
            fi
        fi
    fi
    log "PHP_FPM_INFO, zts=$WEB_ZTS, WHATAP_WEB=$WHATAP_WEB, process=$WHATAP_WEB_PROCESS" true
}

############# PHP Info
get_php_info() {
    php_path=$1
    log "get_php_info ARGS=$php_path" false

    if [ -n "$1" ]; then
        #php bin
        PHP_BIN=$php_path

        # Get PHP API
        #php -i | grep 'PHP API'
        #PHP API => 20131106
        #echo "$php_path -i | grep 'PHP API'"
        PHP_API=`$php_path -i | grep 'PHP API'`
        if [ -n "${PHP_API}" ]; then
             PHP_API=${PHP_API#PHP API => }
             log "PHP API=$PHP_API " true
        else
            log "Error: Not found PHP API" true
        fi

        # Get PHP Thread Safe
        #php -i | grep 'Thread'
        #Thread Safety => disabled

        tmp=`$php_path -i | grep 'Thread'`
        if [ -n "${tmp}" ]; then
            if echo "$tmp" | grep -q "enabled"; then
                PHP_ZTS="_zts"
            fi
            log "PHP_ZTS=$PHP_ZTS" true
        else
            log "Error: Not found PHP_ZTS" true
        fi

        # Get PHP Extension Directory Path (None ZTS)
        #php -i | grep extension_dir | grep -v sqlite
        #extension_dir => /usr/lib64/php/modules => /usr/lib64/php/modules

        tmp=`$php_path -i | grep extension_dir | grep -v sqlite`
        if [ -n "${tmp}" ]; then
            if echo "$tmp" | grep -q "extension_dir"; then
                tmp=${tmp#*=> }
                tmp=${tmp#*=> }
                PHP_EXTENSION_DIR=${tmp}
                log "PHP EXTENSION DIR=$PHP_EXTENSION_DIR" true
            else
                log "Error: PHP Extension directory is none" true
            fi
        else
            log "Error: Not found PHP Extension directory" true
        fi

        # Get PHP Ini Derrctory Path (None ZTS)
        #php -i | grep '.ini files'
        #Scan this dir for additional .ini files => /etc/php.d

        tmp=`$php_path -i | grep 'Scan this dir for additional'`
        if [ -n "${tmp}" ]; then
             if echo "$tmp" | grep -q "ini files"; then
                tmp=${tmp#*=> }
                tmp=${tmp#*=> }
                PHP_INI_DIR=${tmp}
                log "PHP INI DIR=$PHP_INI_DIR" true
            else
                log "Error: PHP ini directory is none" true
            fi
        else
            log "Error: Not found PHP ini directory" true
            PHP_INI_DIR="(none)"
        fi

        # Get PHP Configureation File
        # php -i | grep 'Loaded Configuration File'

        tmp=`$php_path -i | grep 'Loaded Configuration File'`
        if [ -n "${tmp}" ]; then
             if echo "$tmp" | grep -q "Loaded Configuration File"; then
                tmp=${tmp#*=> }
                tmp=${tmp#*=> }
                PHP_CONF_FILE=${tmp}
                log "PHP CONF FILE=$PHP_CONF_FILE" true
            else
                log "Error: PHP Confing file is none" true
            fi
        else
            log "Error: Not found PHP Config file" true
        fi
    else
        log "Error: Not found PHP CLI" true
    fi
}

#################### Copy ini, so, set WHATAP_CONFIG_HOME
process_php() {
    #Confirm PHP INI DIR
    ## PHP INI SCAN DIR is none
    # DEBUG ##############################
    # PHP_INI_DIR="(none)"
    # ##############################
    if [ "${PHP_INI_DIR}" = "(none)" ]; then
        log "PHP_INI_DIR is None" false
        PHP_INI_DIR=${WHATAP_HOME}

        # php.ini
        set_php_conf ${WHATAP_MODULE_FILE}
    fi
    # Ubuntu phpenmod
    #set_whatap_conf_ubuntu
    # linux (Centos), FreeBSD
    set_whatap_conf

    set_whatap_ext

    set_whatap_env
}

get_php_api_version() {
    case "$1" in
        "5.2") PHP_API="20041225" ;;
        "5.3") PHP_API="20090626" ;;
        "5.4") PHP_API="20100412" ;;
        "5.5") PHP_API="20121113" ;;
        "5.6") PHP_API="20131106" ;;
        "7.0") PHP_API="20151012" ;;
        "7.1") PHP_API="20160303" ;;
        "7.2") PHP_API="20170718" ;;
        "7.3") PHP_API="20180731" ;;
        "7.4") PHP_API="20190902" ;;
        "8.0") PHP_API="20200930" ;;
        "8.1") PHP_API="20210902" ;;
        "8.2") PHP_API="20220829" ;;
        "8.3") PHP_API="20230831" ;;
        "8.4") PHP_API="20240924" ;;
        "8.5") PHP_API="20250925" ;;
        *) help ; break ;;
    esac
}

# whatap to php_conf file
# param $1 extension
set_php_conf() {
    log "PHP_CONF_FILE=$PHP_CONF_FILE, WHATAP_EXTENSION=$1"

    ## remove
    remove_php_conf

    # php.ini
    echo "" >> ${PHP_CONF_FILE}
    echo "[${WHATAP_NAME}]" >> ${PHP_CONF_FILE}
    echo "; Enable ${WHATAP_NAME} extension module" >> ${PHP_CONF_FILE}
    echo "extension=$1" >> ${PHP_CONF_FILE}
    echo "${WHATAP_ACCESS_KEY}" >> ${PHP_CONF_FILE}
    echo "${WHATAP_SERVER_HOST}" >> ${PHP_CONF_FILE}
    echo "${WHATAP_NAME}.ext.error_enabled=true" >> ${PHP_CONF_FILE}
    echo "${WHATAP_NAME}.ext.exception_enabled=true" >> ${PHP_CONF_FILE}
    echo "${WHATAP_NAME}.trace_user_enabled=true" >> ${PHP_CONF_FILE}
    echo "${WHATAP_NAME}.trace_user_using_ip=false" >> ${PHP_CONF_FILE}
    echo "; ${WHATAP_NAME}.trace_user_header_ticket=" >> ${PHP_CONF_FILE}
    echo "" >> ${PHP_CONF_FILE}
}

# remove whatap config from php conf file
remove_php_conf() {
    # Remove php.ini
    log "Remove ${WHATAP_NAME} in ${PHP_CONF_FILE}" true
    sed -i "/${WHATAP_NAME}/d" ${PHP_CONF_FILE} 2> /dev/null
}

# set whatap ini
set_whatap_conf() {
    log "Set ${WHATAP_NAME} conf : PHP_INI_DIR=$PHP_INI_DIR" true
    #Copy ini
    destINI="$PHP_INI_DIR/${WHATAP_NAME}.ini"
    srcINI="$WHATAP_INI_TEMPLATE"
    cp -p ${srcINI} ${destINI}

    #Append ini
    sed -i "1i\; Enable ${WHATAP_NAME} extension module" "${destINI}"
    sed -i '2i\extension='${WHATAP_MODULE_FILE} "${destINI}"
    sed -i '3i\'${WHATAP_ACCESS_KEY} "${destINI}"
    sed -i '4i\'${WHATAP_SERVER_HOST} "${destINI}"
    sed -i '5i\'${WHATAP_NAME}'.app_name='${WHATAP_WEB} "${destINI}"
    sed -i '6i\'${WHATAP_NAME}'.app_process_name='${WHATAP_WEB_PROCESS} "${destINI}"

    log "Copy INI to ${destINI}" true

}

set_whatap_conf_ubuntu() {
    ## Ubuntu php enmod
    ## php5.3 Not fount php5enmod
    ## set both php5 and php7
    php5enmod=`which php5enmod 2> /dev/null`
    phpenmod=`which phpenmod 2> /dev/null`

    if [ -n "$php5enmod" ] || [ -n "$phpenmod" ]; then
        if [ -n "$php5enmod" ]; then
            ## Ubuntu    /etc/php5
            tmp=`expr match "$PHP_INI_DIR" '\(.*php.*\)/.*/.*' 2> /dev/null`
            if [ -n "$tmp" ]; then
                PHP_INI_DIR="$tmp/mods-available"
            else
                ## Ubuntu    /etc/php/7.0
                tmp=`expr match "$PHP_INI_DIR" '\(.*php/[0-9][.][0-9]\)/.*' 2> /dev/null`
                if [ -n "$tmp" ]; then
                   PHP_INI_DIR="$tmp/mods-available"
                fi
            fi
            set_whatap_conf

            php5enmod ${WHATAP_NAME}
            log "php5enmod ${WHATAP_NAME}" true
        fi

        if [ -n "$phpenmod" ]; then
            ## Ubuntu    /etc/php5
            tmp=`expr match "$PHP_INI_DIR" '\(.*php.*\)/.*/.*' 2> /dev/null`
            if [ -n "$tmp" ]; then
                PHP_INI_DIR="$tmp/mods-available"
            else
                ## Ubuntu    /etc/php/7.0
                tmp=`expr match "$PHP_INI_DIR" '\(.*php/[0-9][.][0-9]\)/.*' 2> /dev/null`
                if [ -n "$tmp" ]; then
                   PHP_INI_DIR="$tmp/mods-available"
                fi
            fi
            set_whatap_conf

            phpenmod ${WHATAP_NAME}
            log "phpenmod ${WHATAP_NAME}" true
        fi
    else
        set_whatap_conf
    fi
}

set_whatap_ext() {
    #Copy Library(.so)
    destSo="$PHP_EXTENSION_DIR/${WHATAP_MODULE_FILE}"
    srcSo="${WHATAP_MODULES}/${WHATAP_BUILD_ARCH}/${WHATAP_NAME}${PHP_ZTS}_${PHP_API}.so"
    PHP_EXTENSION_SRC=${srcSo}

    #Check Modules
    if [ -f "$srcSo" ]; then
        # cp ${srcSo} ${destSo}
        # log "Copy Module to $destSo" true

        ln -sf ${srcSo} ${destSo}
        log "Link Module $srcSo to $destSo" true
    else
        log "Error Not found module, name=$srcSo" true
    fi
}

# edit /etc/init.d/whatap-php
set_whatap_env() {
    sed -i "/WHATAP_CONFIG_HOME=/ c export WHATAP_CONFIG_HOME=$PHP_INI_DIR" ${WHATAP_SERVICE_FILE}
    sed -i "/WHATAP_PHP_EXT_HOME=/ c export WHATAP_PHP_EXT_HOME=$PHP_EXTENSION_DIR" ${WHATAP_SERVICE_FILE}
    sed -i "/WHATAP_PHP_EXT_SRC=/ c export WHATAP_PHP_EXT_SRC=$PHP_EXTENSION_SRC" ${WHATAP_SERVICE_FILE}
    sed -i "/WHATAP_PHP_BIN=/ c export WHATAP_PHP_BIN=$PHP_BIN" ${WHATAP_SERVICE_FILE}

}

###########################################
# read the options
# Parameter is mandatory (indicated by :)
# Parameter is options (indicated by ::)
###########################################

TEMP=`getopt -o v:i:e:z::p:l:s:h --long php-version:,php-ini:,php-exe:,php-zts::,process-name:,license:,accesskey:,server:,help -- "$@"`
eval set -- "$TEMP"

# extract options and their arguments into variables.
while true ; do

    case "$1" in
        -v|--php-version)
            SET_PHP_VERSION=$2 ; shift 2 ;;
        -i|--php-ini)
            SET_PHP_INI=$2 ; shift 2 ;;
        -e|--php-exe)
            SET_PHP_BIN=$2 ; shift 2 ;;
        -z|--php-zts)
            SET_PHP_ZTS="_zts" ; shift 2 ;;
        -p|--process-name)
            SET_PROCESS_NAME=$2 ; shift 2 ;;
        -l|--license|--accesskey)
            WHATAP_ACCESS_KEY="${WHATAP_NAME}.accesskey=$2" ; shift 2 ;;
        -s|--server)
            WHATAP_SERVER_HOST="${WHATAP_NAME}.server.host=$2" ; shift 2 ;;
        -h|--help)
            help ; exit 2 ;;
        --) shift ; break ;;
        *) help ; break ;;
    esac
done


log "SET_PHP_BIN=$SET_PHP_BIN" false
log "SET_PHP_VERSION=$SET_PHP_VERSION" false
log "SET_PHP_INI=$SET_PHP_INI" false
log "SET_PHP_THREAD=$SET_PHP_ZTS" false
log "SET_PROCESS_NAME=$SET_PROCESS_NAME" false

log $INSTALL_TARGET false

## Validate
case "$INSTALL_TARGET" in
    "auto") ;;
    "manual");;
    "remove");;
    *)
        if [ -z "${WHATAP_ACCESS_KEY}" -o -z "$WHATAP_SERVER_HOST}" ]; then
            log "Error. Access key or ${WHATAP_NAME}.server not found" true
            help
            exit 2;
        fi

        if [ -n "${SET_PHP_BIN}" ]; then
            if [ -n "${SET_PROCESS_NAME}" ]; then
                INSTALL_TARGET="php-exe"

                get_php_info ${SET_PHP_BIN}

                PHP_BIN=${SET_PHP_BIN}
                #PHP_INI_DIR=${WHATAP_HOME}
                #PHP_EXTENSION_DIR="${WHATAP_MODULES}/${WHATAP_BUILD_ARCH}"
                #PHP_ZTS=${SET_PHP_ZTS}

                WHATAP_WEB_PROCESS=${SET_PROCESS_NAME}
                WHATAP_WEB=${SET_PROCESS_NAME}

            else
                log "Error. process-name not found" true
                help
                exit 2;
            fi
        else
            if [ -n "${SET_PHP_VERSION}" ] && [ -n "${SET_PHP_INI}" ] && [ -n "${SET_PROCESS_NAME}" ]; then
                INSTALL_TARGET="php-version"

                get_php_api_version ${SET_PHP_VERSION}
                PHP_CONF_FILE=${SET_PHP_INI}
                PHP_BIN=${SET_PHP_BIN}
                PHP_INI_DIR=${WHATAP_HOME}
                PHP_EXTENSION_DIR="${WHATAP_MODULES}/${WHATAP_BUILD_ARCH}"
                PHP_ZTS=${SET_PHP_ZTS}

                WHATAP_WEB_PROCESS=${SET_PROCESS_NAME}
                WHATAP_WEB=${SET_PROCESS_NAME}

                log "PHP_API_VERSION=$PHP_API" true
            else
                if [ -z "${SET_PHP_VERSION}" ]; then
                    log "Error. php-version not found" true
                fi
                if [ -z "${SET_PHP_INI}" ]; then
                    log "Error. php-ini not found" true
                fi
                if [ -z "${SET_PROCESS_NAME}" ]; then
                    log "Error. process-name not found" true
                fi

                help
                exit 2;
            fi
        fi
        ;;
esac

###############################################
## main
###############################################

# 1. Get arch
get_build_arch

# 2.install with command 
case "$INSTALL_TARGET" in
    auto)
        log "INIT Instal auto" false

        ####### Start
        # scan env
        get_env

        ## Read input
        read_input

        ## WEB , PHP_FPM info
        if $IS_APACHECTL; then
            log "Find APACHECTL" true
            ## apache info
            get_apache_info $PATH_APACHECTL
            #### PHP
            if [ -n "${WEB_ZTS}" ]; then
                if $IS_PHP_ZTS || $IS_ZTS_PHP; then
                    get_php_info $PATH_PHP_ZTS
                elif $IS_PHP || $IS_PHP5; then
                    get_php_info $PATH_PHP
                fi
            else
                if $IS_PHP || $IS_PHP5; then
                    get_php_info $PATH_PHP
                fi
            fi
        elif $IS_APACHE || $IS_APACHE2; then
            log "Find APACHE" true
            ## apache info
            get_apache_info $PATH_APACHE
            #### PHP
            if [ -n "${WEB_ZTS}" ]; then
                if $IS_PHP_ZTS || $IS_ZTS_PHP; then
                    get_php_info $PATH_PHP_ZTS
                elif $IS_PHP || $IS_PHP5; then
                    get_php_info $PATH_PHP
                fi
            else
                if $IS_PHP || $IS_PHP5; then
                    get_php_info $PATH_PHP
                fi
            fi
        elif $IS_PHP_FPM || $IS_PHP5_FPM; then
            log "Find PHP-FPM" true
            ## php-fpm info
            get_php_fpm_info $PATH_PHP_FPM
            get_php_info $PATH_PHP_FPM
        fi

        #### Process edit, copy - so, ini, whatap-php
        process_php

        ## Service Boot Autorun
        make_init

        ## Start Service
        restart_agent

        log "" true
        log "Please Restart Apache & PHP-FPM." true
        log "Then ${WHATAP_PACKAGE_NAME} agent starts collecting application monitoring data." true
        log "" true
        ;;
    manual)
        log "INIT Instal manual" false
        read_manual

        # to lowercase
        tmp=`echo $MANUAL_WHICH_WEB | tr '[A-Z]' '[a-z]'`
        if echo ${tmp} | grep -q 'apache' || echo ${tmp} | grep -q 'http'; then
            get_apache_info ${MANUAL_WHICH_WEB}
        else
            get_php_fpm_info ${MANUAL_WHICH_WEB}
            MANUAL_WHICH_PHP=$MANUAL_WHICH_WEB
        fi

        get_php_info ${MANUAL_WHICH_PHP}

        #### Process edit, copy - so, ini, whatap-php
        process_php

        ## Service Boot Autorun
        make_init

        ## Start Service
        restart_agent

                log "" true
                log "Please Restart Apache & PHP-FPM." true
                log "Then ${WHATAP_PACKAGE_NAME} agent starts collecting application monitoring data." true
                log "" true
        ;;
    remove)
        log "INIT Instal remove" false

        make_remove
        log "" true
        ;;
    php-exe)
        # option php-exe
        log "php-exe=$PHP_BIN, process-name=$WHATAP_WEB_PROCESS"

        ## lecense and server host

        ## get php info
        get_php_info ${SET_PHP_BIN}

        ## Process edit, copy - so, ini, whatap-php
        process_php

        ## Service Boot Autorun
        make_init

        ## Start Service
        restart_agent

        log "" true
        log "Please Restart Apache & PHP-FPM." true
        log "Then ${WHATAP_PACKAGE_NAME} agent starts collecting application monitoring data." true
        log "" true

        ;;
    php-version)
        ## option php-version
        log "php-version=$PHP_API, php-ini=$PHP_CONF_FILE, process-name=$WHATAP_WEB_PROCESS" true

        ## lecense and server host

        ## set php env
        PHP_INI_DIR=${WHATAP_HOME}
        PHP_EXTENSION_DIR="${WHATAP_MODULES}/${WHATAP_BUILD_ARCH}/"
        PHP_BIN=`which php 2> /dev/null`
        PHP_EXTENSION_SRC="${WHATAP_MODULES}/${WHATAP_BUILD_ARCH}/${WHATAP_NAME}${PHP_ZTS}_${PHP_API}.so"
        # WHATAP_WEB
        # WHATAP_WEB_PROCESS

        ## configure whatap.ini
        set_whatap_conf

        ## configure whatap module
        # whatap to php conf file(php.ini)
        set_php_conf "${PHP_EXTENSION_SRC}"

        ## configure whatap agent service
        set_whatap_env

        ## Service Boot Autorun
        make_init

        ## Start Service
        restart_agent

        log "" true
        log "Please Restart Apache & PHP-FPM." true
        log "Then ${WHATAP_PACKAGE_NAME} agent starts collecting application monitoring data." true
        log "" true
        ;;
    *)
        help
        exit 2
        ;;
esac
