#!/usr/bin/bash
#Tate:2022.3.22
#Author:Yingjian
#Function：一键编译安装nginx

#判断是否已安装nginx
num=`ps -ef |grep -v grep |grep nginx |wc -l`
if [ ! $num -eq 0 ];then
echo "nginx 服务已存在"
exit 2    
fi

if [ -d "/usr/local/nginx" ];then
echo "nginx 已安装" 
exit 2
fi
#判断网络是否正常
ping -c 1 www.baidu.com &> /dev/null
if [ ! $? -eq 0 ];then
echo "请检测网络是否正常"
exit 2
fi

if [ ! -f "/usr/local/src/nginx-1.20.0.tar.gz" ];then
curl -o /usr/local/src/nginx-1.20.0.tar.gz -s http://8.210.62.122/nginx/nginx-1.20.0.tar.gz
else
echo "nginx包已安装"
fi

#安装依赖
yum -y install gcc  gcc-c++  make pcre-devel zlib-devel openssl-devel &>/dev/null

#解压
tar xf /usr/local/src/nginx-1.20.0.tar.gz -C /usr/local

#创建启动用户
id nginx
if [ ! $? -eq 0 ];then
useradd -M nginx -s /sbin/nologin
else
echo "nginx用户已创建"
fi

#编译安装
cd /usr/local/nginx-1.20.0
./configure  --prefix=/usr/local/nginx  --sbin-path=/usr/local/nginx/sbin/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/var/log/nginx/error.log  --http-log-path=/var/log/nginx/access.log  --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock  --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --http-client-body-temp-path=/var/tmp/nginx/client/ --http-proxy-temp-path=/var/tmp/nginx/proxy/ --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi --http-scgi-temp-path=/var/tmp/nginx/scgi --with-pcre
if [ ! $? -eq 0 ];then
echo "configure 失败 请清理环境 重新安装"
exit 3
fi

make -j `cat /proc/cpuinfo | grep processor| wc -l` && make install

if [ ! $? -eq 0 ];then
echo "make 失败 请清理环境 重新安装"
exit 4
fi

#创建临时目录
mkdir -p /var/tmp/nginx/client

cat > /usr/lib/systemd/system/nginx.service <<EOF
# /usr/lib/systemd/system/nginx.service
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target sshd-keygen.service

[Service]
Type=forking
EnvironmentFile=/etc/sysconfig/sshd
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
Restart=on-failure
RestartSec=42s

[Install]
WantedBy=multi-user.target
EOF

/usr/local/src/nginx-1.20.0.tar.gz
#设置开机自启

systemctl daemon-reload
systemctl enable nginx
systemctl restart nginx

echo "--------------nginx 安装完成-----------"

