#!/bin/bash

. /etc/init.d/functions
set -u
#配置变量
download_url="http://nginx.org/download/"
Nginx_source_zip="nginx-1.22.0.tar.gz"
Install_Path="/usr/local/"
Instll_Dir="nginx"
User="nginx"
red="\033[31m"
red_warn="\033[5;31m"
green="\033[32m"
color_end="\033[0m"
Pid_Path="${Install_Path}${Instll_Dir}/logs/nginx.pid"
#安装依赖 
echo "正在安装所需依赖"
yum install wget gcc openssl-devel zlib zlib-devel  pcre-devel make gcc-c++ -y 
if [[ $? == 0 ]];then
	action  "依赖安装完成"  /bin/true
else
	action "依赖安装失败" /bin/false
fi
#创建用户
if  ! id $User &>/dev/null ;then
	useradd -r $User -s /sbin/nologin &>/dev/null
	if [ $? -eq 0 ];then
		action "用户创建成功!"   /bin/true
	fi
else
	echo -e "${red}${User}用户已存在,无需创建!${color_end}"
fi

#下载nginx源码包
if  [[ ! -f ${Nginx_source_zip} ]]; then
	wget --show-progress -q -O  ${Nginx_source_zip} ${download_url}${Nginx_source_zip} 
else
	echo -e "${red}${Nginx_source_zip}已存在,无需下载!${color_end}"
fi

#解压缩
if ! [ -d ${Nginx_source_zip%.tar.gz} ];then
	echo -e "${red}正在解压缩中${color_end}"
	tar -xf ${Nginx_source_zip} &>/dev/null
else
	echo -e "${red}源码包已存在无需解压${color_end}"
fi

#准备编译

cd ${Nginx_source_zip%.tar.gz}

./configure  --prefix=${Install_Path}${Instll_Dir} --user=$User --pid-path=$
  {Pid_Path} --group=$User --with-http_stub_status_module --with-http_ssl_module
  --with-http_gzip_static_module --with-http_gunzip_module --with-http_flv_module
  --with-http_v2_module --with-http_auth_request_module  &>$
  {HOME}/configure_err.log

if [ $? -eq 0 ];then
	make  && make install 
else
	action "configure配置失败,请查看日志${HOME}/configure_err.log" /bin/false
	exit
fi

chown -R nginx. ${Install_Path}${Instll_Dir}

#配置nginxPATH
echo PATH=$PATH:"${Install_Path}${Instll_Dir}/sbin" > /etc/profile.d/nginx_path.sh
source /etc/profile.d/nginx_path.sh


#配置systemd管理
Nginx_Service(){
cat >>/usr/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
# Nginx will fail to start if /run/nginx.pid already exists but has the wrong
# SELinux context. This might happen when running 'nginx -t' from the cmdline.
# https://bugzilla.redhat.com/show_bug.cgi?id=1268621
ExecStartPre=/usr/bin/rm -f ${PIDFile}
ExecStartPre=${Install_Path}${Instll_Dir}/sbin/nginx -t
ExecStart=${Install_Path}${Instll_Dir}/sbin/nginx
ExecReload=/bin/kill -s HUP \$MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=mixed
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF
}

set +u
#写入文件使用systemd管理
Nginx_Service
if ! [ $? -eq 0 ];then
	action  "加入systemd失败请检查脚本" /bin/false
	exit 
fi

#重载systemd并启动
if  systemctl daemon-reload ;then
	if  systemctl start nginx;then
		action "nginx 安装启动完成!" /bin/true
 		rm -rf ./${Nginx_source_zip} ./${Nginx_source_zip%.tar.gz} ./configure_err.log
    else
		echo -e "${red}nginx 启动失败,请查看日志!${color_end}"
	fi
fi


