#!/bin/bash

echo "nginx升级现在开始"
sleep 2
chown -R root:root `pwd`
while read -p "请输入原安装路径 (格式:/\$dir/\$dir):" DIR;do
  if [ "$DIR" = "" ];then
    echo "值为空，请重新输入"
  else
    :
    break
  fi
done

Dire(){
if [ ! -d "$DIR" ];then
  echo "原安装路径不存在,请检查"
  exit 10
else
  :
fi

if [ ! -f "$DIR/sbin/nginx" ];then
  echo "原安装目录下nginx二进制文件不存在,请检查"
  exit 10
fi

if [ ! -f "$DIR/nginx.pid" ];then
  echo "nginx.pid文件不存在,请检查nginx运行情况"
  exit 10
fi
}

Dire

Appli(){
echo "现在检查yum源情况"
sleep 2
if [ -f -a "/etc/yum.repos.d/*.repo" ];then
  echo "yum源存在"
else
  echo "yum源不存在，请检查"
  exit 10
fi

echo "下面开始下载依赖插件"
sleep 2
yum -y install gcc-c++
}

Appli

confi(){
echo "下面开始进行编译"
tar xf openssl-1.1.1b.tar.gz
tar xf pcre-8.45.tar.gz
tar xf zlib-1.2.11.tar.gz
sleep 2
if [ -f "Makefile" ];then
  make clean
fi
./configure \
--prefix=$DIR \
--sbin-path=$DIR/sbin/nginx  \
--modules-path=$DIR/modules \
--conf-path=$DIR/conf/nginx.conf \
--error-log-path=$DIR/log/error.log \
--http-log-path=$DIR/log/access.log  \
--pid-path=$DIR/nginx.pid  \
--lock-path=$DIR/nginx.lock  \
--http-client-body-temp-path=$DIR/client_temp \
--http-proxy-temp-path=$DIR/proxy_temp \
--http-fastcgi-temp-path=$DIR/fastcgi_temp \
--http-uwsgi-temp-path=$DIR/uwsgi_temp \
--http-scgi-temp-path=$DIR/scgi_temp \
--with-compat \
--user=nginx  \
--group=nginx \
--with-openssl=openssl-1.1.1b \
--with-pcre=pcre-8.45/ \
--with-zlib=zlib-1.2.11/ \
--with-file-aio \
--with-threads \
--with-http_addition_module \
--with-http_auth_request_module \
--with-http_dav_module \
--with-http_flv_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_mp4_module \
--with-http_random_index_module \
--with-http_realip_module \
--with-http_secure_link_module \
--with-http_slice_module \
--with-http_ssl_module \
--with-http_stub_status_module \
--with-http_sub_module \
--with-http_v2_module \
--with-mail \
--with-mail_ssl_module \
--with-stream \
--with-stream_realip_module \
--with-stream_ssl_module \
--with-stream_ssl_preread_module \

make

if [ $? != 0 ];then
  echo "!!编译失败，请检查!!"
  rm -rf {openssl-1.1.1b,pcre-8.45,zlib-1.2.11}
  exit 99
else
  echo "编译成功"
  rm -rf {openssl-1.1.1b,pcre-8.45,zlib-1.2.11}
fi

#校验新nginx版本编译的二进制文件
objs/nginx -t -c $DIR/conf/nginx.conf
if [ $? -eq 0 ];then
  echo "编译二进制文件校验成功"
else
  echo "编译二进制文件校验失败,请检查"
  exit 10
fi
}

confi

ng_update(){
#备份原二进制文件
mv $DIR/sbin/nginx $DIR/sbin/nginx.bak_`date +%F`
#复制编译好的二进制文件到原nginx目录
cp objs/nginx $DIR/sbin/

#发送信号:USR2,WINCH
kill -USR2 `cat $DIR/nginx.pid`
sleep 2
if [ ! -f "$DIR/nginx.pid.oldbin" ];then
  echo "新的nginx进程号未生成,请检查"
  exit 10
fi

kill -WINCH `cat $DIR/nginx.pid.oldbin`
sleep 2
if [ "`ps -ef | grep 'nginx: master process' | grep -v 'grep' | wc -l`" -lt 2 ];then
  echo "新进程未启动,请检查"
  exit 10
fi

#发送退出信号:QUIT
kill -QUIT `cat $DIR/nginx.pid.oldbin`

echo "nginx升级成功"
$DIR/sbin/nginx -v
}
ng_update
