#!/bin/sh
# functions - install modules
# @function install Nginx-Server
function InstallST2Nginx()
{
    local proc_=$1 usrc_= utgt_= tmp_= y_= id_=1 poolsize_=3

    if [ "${_WEB_SERVER_TYPE_}" = "httpd" ]; then
        return
    fi
    
    ShowResult "[green]正在安装Nginx服务器... [/green]" 1
    
    cd ${_PATH_COMPILATION_}
    # prepare
    eval rm -rf ./nginx-1.* ${_SYS_SHOW_INSTALL_DETAILS_}
    eval rm -rf ./zlib-1.* ${_SYS_SHOW_INSTALL_DETAILS_}
    eval rm -rf ./openssl-1.* ${_SYS_SHOW_INSTALL_DETAILS_}
    eval tar zxvf ${_PATH_SOFTWARE_}/nginx-1.* ${_SYS_SHOW_INSTALL_DETAILS_}
    eval tar xvf ${_PATH_SOFTWARE_}/zlib-1.* ${_SYS_SHOW_INSTALL_DETAILS_}
    eval tar xvf ${_PATH_SOFTWARE_}/openssl-1.* ${_SYS_SHOW_INSTALL_DETAILS_}

    # install
    eval cd nginx-1.* ${_SYS_SHOW_INSTALL_DETAILS_}
    eval ./configure \
        --prefix=/usr/local/nginx \
        --with-http_v2_module \
        --with-http_ssl_module \
        --with-http_realip_module \
        --with-http_addition_module \
        --with-http_sub_module \
        --with-http_dav_module \
        --with-http_flv_module \
        --with-http_mp4_module \
        --with-http_gunzip_module \
        --with-http_gzip_static_module \
        --with-http_random_index_module \
        --with-http_secure_link_module \
        --with-http_stub_status_module \
        --with-http_auth_request_module \
        --with-mail \
        --with-mail_ssl_module \
        --with-file-aio \
        --with-ipv6 \
        --with-http_v2_module \
        --with-threads \
        --with-stream \
        --with-stream_ssl_module \
        --with-pcre \
        --with-zlib=${_PATH_COMPILATION_}/zlib-1.2.11 \
        --with-openssl=${_PATH_COMPILATION_}/openssl-1.*\
        --with-ld-opt="-ljemalloc"
        ${_SYS_SHOW_INSTALL_DETAILS_}
    eval make ${_SYS_MAKE_EXT_} ${_SYS_SHOW_INSTALL_DETAILS_}
    eval make install ${_SYS_SHOW_INSTALL_DETAILS_}
    
    ShowStatus $? 1

    if [ ! -z "${proc_}" ]; then
        eval mv -f /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/${proc_} ${_SYS_SHOW_INSTALL_DETAILS_}
    fi
    
    eval \cp -f ${_PATH_CONFIGS_}/nginx.conf /usr/local/nginx/conf/nginx.conf ${_SYS_SHOW_INSTALL_DETAILS_}
    eval \cp -f ${_PATH_CONFIGS_}/nginx.init.sh /etc/init.d/nginx ${_SYS_SHOW_INSTALL_DETAILS_}
    
    mkdir -p /usr/local/nginx/conf/upstream.conf.d /usr/local/nginx/conf/vhosts.conf.d

    usrc_=${_PATH_CONFIGS_}/nginx-conf/upstream.conf.d/upstream.conf.tpl
    utgt_=/usr/local/nginx/conf/upstream.conf.d/upstream.conf
    eval \cp -f ${usrc_} ${utgt_}
    tmp_=$(sed -rn '/\{POOL_ID\}/p' ${utgt_})
    while [ ! -z "${tmp_}" ] && [ ${id_} -le ${poolsize_} ]; do
        y_="${y_:+${y_}\n}${tmp_//\{POOL_ID\}/${id_}}"
        let id_++
    done
    sed -ri "s@.*\{POOL_ID\}.*@${y_}@g" ${utgt_}
    
    chmod 755 /etc/init.d/nginx 2>&1 > /dev/null
    chkconfig --add nginx 2>&1 > /dev/null
    chkconfig nginx on 2>&1 > /dev/null
    
    ShowStatus $?
}