#!/bin/bash
#
#*****************************************************
#File Name    : install_tengine.sh
#Author       : guokai
#Mail         : xxx@163.com
#Create Time  : 2022-04-11 15:51:15
#Description  : tengine-2.3.3
#*****************************************************
SRC_DIR=/usr/local/src
TENGINE_URL=http://58.220.50.162:7777/download/
TENGINE_FILE=tengine-3.1.0
TAR=.tar.gz
TENGINE_INSTALL_DIR=/home/tengine
CPUS=`lscpu | awk '/^CPU\(s\)/{print $2}'`
NGINX_LOGFILEDIR=/home/logs

color () {
	RES_COL=60
	MOVE_TO_COL="echo -en \\033[${RES_COL}G"
	SETCOLOR_SUCCESS="echo -en \\033[1;32m"
	SETCOLOR_FAILURE="echo -en \\033[1;31m"
	SETCOLOR_WARNING="echo -en \\033[1;33m"
	SETCOLOR_NORMAL="echo -en \E[0m"
	echo -n "$2" && $MOVE_TO_COL
	echo -n "["
	if [ $1 = "success" -o $1 = "0" ] ;then ${SETCOLOR_SUCCESS}
		echo -n $"  OK  "
	elif [ $1 = "failure" -o $1 = "1" ] ;then ${SETCOLOR_FAILURE}
		echo -n $"FAILED"
	else 
		${SETCOLOR_WARNING}
		echo -n $"WARNING"
	fi
	${SETCOLOR_NORMAL}
	echo -n "]"
	echo
}

os_type () {
	awk -F '[ "]' '/^NAME/{print $2}' /etc/os-release
}
os_version () {
	awk -F '"' '/^VERSION_ID/{print $2}' /etc/os-release
}

check () {
	[ -e ${TENGINE_INSTALL_DIR} ] && { color 1 "tengine 已安装,请卸载后再安装" ; exit; }
	cd ${SRC_DIR}
	if [ -e ${TENGINE_FILE}${TAR} ];then
		color 0 "相关文件已准备好"
	else
		color 0 "开始下载 tengine 源码包"
		wget ${TENGINE_URL}${TENGINE_FILE}${TAR}
		[ $? -ne 0 ] && { color 1 "下载 ${TENGINE_FILE}${TAR}文件失败" ; exit ; }
	fi
}

install (){
	color 0 "开始安装 tengine"
	if id nginx &> /dev/null ; then
		color 1 "nginx 用户已存在"
	else 
		useradd -s /sbin/nologin -r nginx
		color 0 "创建 nginx 用户"
	fi
	color 0 "开始安装 tengine 依赖包"
	if [ `os_type` == "CentOS" -a `os_version` == '8' ];then
		yum install -y -q make gcc-c++ libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel perl-ExtUtils-Embed unzip
	elif [ `os_type` == "CentOS" -a `os_version` == '7' ];then
		yum install -y  make gcc pcre-devel openssl-devel zlib-devel perl-ExtUtils-Embed unzip
	else
		dnf -y install make gcc  openssl   pcre pcre-devel  openssl openssl-devel  zlib zlib-devel  #&> /dev/null
	fi
}

make_install() {

#编译安装tengine
cd $SRC_DIR
tar xf ${TENGINE_FILE}${TAR}
TENGINE_DIR=`echo ${TENGINE_FILE}${TAR}| sed -nr 's/^(.*[0-9]).*/\1/p'`
cd ${SRC_DIR}/${TENGINE_DIR}
./configure --prefix=${TENGINE_INSTALL_DIR} --with-http_ssl_module --with-http_flv_module --with-http_stub_status_module \
--with-http_gzip_static_module --with-http_realip_module --with-pcre  --with-stream --add-module=$SRC_DIR/${TENGINE_DIR}/modules/ngx_http_upstream_check_module
 
make -j $CPUS && make install
[ $? -eq 0 ] && color 0 "tengine 编译安装成功" || { color 1 "tengine 编译安装失败,退出!" ;exit; }
echo "PATH=${TENGINE_INSTALL_DIR}/sbin:${PATH}" >> /etc/profile.d/nginx.sh

}

config (){
	mv $TENGINE_INSTALL_DIR/conf/nginx.conf $TENGINE_INSTALL_DIR/conf/nginx.confbak
	mkdir -p $NGINX_LOGFILEDIR
	cat > $TENGINE_INSTALL_DIR/conf/nginx.conf << EOF
user  nginx;
worker_processes  auto;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#error_log  "pipe:rollback logs/error_log interval=1d baknum=7 maxsize=2G";

pid        ${TENGINE_INSTALL_DIR}/logs/nginx.pid;


events {
    worker_connections  65535;
}


http {
    #resolver 114.114.114.114; # replace it with your favorite config
    #charset UTF-8;
    include       mime.types;
    default_type  application/octet-stream;

log_format  json '{"@timestamp":"\$time_iso8601",'
'"host":"\$server_addr",'
'"clientip":"\$http_x_forwarded_for",'
'"http_user_agent":"\$http_user_agent",'
'"http_x_forwarded_for":"\$http_x_forwarded_for",'
'"size":\$body_bytes_sent,'
'"responsetime":\$request_time,'
'"upstreamtime":"\$upstream_response_time",'
'"upstreamhost":"\$upstream_addr",'
'"http_host":"\$host",'
'"request":"\$request",'
'"url":"\$uri",'
'"xff":"\$remote_addr",'
'"referer":"\$http_referer",'
'"agent":"\$http_user_agent",'
'"status":"\$status"}';
    access_log  $NGINX_LOGFILEDIR/access.log  json;
    error_log $NGINX_LOGFILEDIR/error.log debug;


    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;
    #gzip  on;
    #client_header_buffer_size 256k;
    #client_body_buffer_size 5m;
    #client_max_body_size 20m;
    #proxy_buffer_size 128k;
    #proxy_buffers 64 128k;
    #proxy_busy_buffers_size 5m;
    #proxy_temp_file_write_size 512k;


 
	#nacos集群负载均衡
#    upstream nacos {
#        server 172.16.72.151:8848;
#        server 172.16.72.152:8848;
#        server 172.16.72.153:8848;
#   	    check interval=1000 rise=30 fall=1 timeout=1000 default_down=false  type=http port=8848;
#     	check_keepalive_requests 1000;
#   	    check_http_send "HEAD /actuator/health HTTP/1.0\r\n\r\n";
#     	check_http_expect_alive http_2xx http_3xx;
#
#    }
#	#方太号码绑定关系负载
#	upstream fangtai_server{
#	   server 172.16.72.151:10120 max_fails=3 fail_timeout=30s;
#	   server 172.16.72.152:10120 max_fails=3 fail_timeout=30s;
#	   server 172.16.72.153:10120 max_fails=3 fail_timeout=30s;
#	   check interval=1000 rise=30 fall=1 timeout=1000 default_down=false  type=http port=10120;
#	   check_keepalive_requests 1000;
#	   check_http_send "HEAD /actuator/health HTTP/1.0\r\n\r\n";
#	   check_http_expect_alive http_2xx http_3xx;
#
#	}	
#


#80端口配置
    server {
        listen       80;
	#listen       443 ssl;
        server_name  localhost;
	#ssl_session_cache    shared:SSL:20m;
        #ssl_session_timeout  4h;
        #server_name  mtnj-recordupload.linkcircle.cn;
        #ssl_certificate     /usr/local/nginx/5756536__linkcircle.cn.pem;
        #ssl_certificate_key  /usr/local/nginx/5756536__linkcircle.cn.key;
        #ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        #ssl_ciphers AES256-SHA256:RC4:HIGH:!MD5:!aNULL:!eNULL:!NULL:!DH:!EDH:!AESGCM;
        #ssl_prefer_server_ciphers  on;

        location / {
            root   html;
            index  index.html index.htm;
        }
#location /fangtai-hmyc{
#
#     proxy_set_header Host $http_host;
#     proxy_set_header X-Real-IP $remote_addr;
#     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#     add_header backendIP $upstream_addr;
#     add_header backendCode $upstream_status;
#     proxy_pass http://fangtai_server/fangtai-hmyc;
#  }
#        #error_page  404              /404.html;
#
#        # redirect server error pages to the static page /50x.html
#        #
#        error_page   500 502 503 504  /50x.html;
#        location = /50x.html {
#            root   html;
#        }
#
#    }
#server {
#        listen       8848;
#        server_name  nacos;
#                 
#        location /nacos/ {
#            #root   html;
#            #index  index.html index.htm;
#            proxy_pass http://nacos/nacos/;
#        }
#        
#        error_page   500 502 503 504  /50x.html;
#        location = /50x.html {
#            root   html;
#        }
    }

}

	
EOF

#创建service文件
	cat > /lib/systemd/system/nginx.service <<EOF
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=${TENGINE_INSTALL_DIR}/logs/nginx.pid
ExecStartPre=/bin/rm -f ${TENGINE_INSTALL_DIR}/logs/nginx.pid
ExecStartPre=${TENGINE_INSTALL_DIR}/sbin/nginx -t
ExecStart=${TENGINE_INSTALL_DIR}/sbin/nginx
ExecReload=/bin/kill -s HUP \$MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
    systemctl enable --now nginx &> /dev/null 
    systemctl is-active nginx &> /dev/null &&  color 0 "tengine 安装完成" ||  { color 1 "tengine 启动失败,退出!"  ; exit; }
	echo '安装完成后，请更新配置文件，配置日志切割logrotate！'


	cat > /etc/logrotate.d/tengine << EOF
$NGINX_LOGFILEDIR/*.log {
        daily
        rotate 30
        compress
        delaycompress
        missingok
        notifempty
        create 664 root root
        postrotate
                if [ -f ${TENGINE_INSTALL_DIR}/logs/nginx.pid ]; then
                        kill -USR1 \`cat ${TENGINE_INSTALL_DIR}/logs/nginx.pid\`
                fi
        endscript
}	
EOF

systemctl reload nginx
ss -tnlp
}


#安装独立的模块lua3.1.0不可用
lua (){
	cd $SRC_DIR
	tar xf ${TENGINE_FILE}${TAR}
	TENGINE_DIR=`echo ${TENGINE_FILE}${TAR}| sed -nr 's/^(.*[0-9]).*/\1/p'`
	cd ${TENGINE_DIR}/modules/
	wget http://58.220.50.162:7777/download/lua-nginx-module-0.10.26.tar.gz && tar -xf lua-nginx-module-0.10.26.tar.gz || { color 1 "解压失败，退出！" ; exit; }
	wget http://58.220.50.162:7777/download/luajit2-2.1-20210510.tar.gz && tar -zxf luajit2-2.1-20210510.tar.gz
	wget http://58.220.50.162:7777/download/v0.3.3.tar.gz && tar -zxf v0.3.3.tar.gz
	cd $SRC_DIR/$TENGINE_DIR/modules/luajit2-2.1-20210510
	make -j $CPUS PREFIX=/usr/local/luajit
	make install PREFIX=/usr/local/luajit
	cp /usr/local/luajit/lib/libluajit-5.1.so.2 /usr/lib64/libluajit-5.1.so.2
	cat > /etc/profile.d/luajit.sh << EOF
export LUAJIT_LIB=/usr/local/luajit/lib
export LUAJIT_INC=/usr/local/luajit/include/luajit-2.1
EOF

. /etc/profile.d/luajit.sh
}
check
install
make_install
config