#!/bin/bash
#AUTHOR:AN
#VERSION:1.1.0
#DATE:2019-04-19
#MODIFY:2019-05-14 2019-05-31
#DESCRIBE:一键部署Nginx
#PEOBLEM:1.生成证书交互失败
# 2.进度条有杀死进程的信息出来,把后面的程序全删除就正常,用整行注释依旧有错误信息

#加载配置文件
source /cloud_nsd/conf/lnmp.conf
#加载函数库
if [ -f "$Script_Path/myfunction.lib" ];then
source $Script_Path/myfunction.lib
else
echo -e "\033[31m函数库不存在\033[0m"
exit $NOEXIST
fi

##############################################################
#用户认证
user_cert(){
read -p "域名:" Domain
read -p "网页文件根目录:" DocumentRoot
MKDIR /usr/local/nginx/$DocumentRoot
echo "$Domain TEST" > /usr/local/nginx/$DocumentRoot/index.html #创建测试页
#添加配置文件
sed -i '$d' /usr/local/nginx/conf/nginx.conf #删除最后一行的}
cat >> /usr/local/nginx/conf/nginx.conf <<EOF
server {
listen 80;
server_name $Domain;
auth_basic "Input Password"; #认证提示符
auth_basic_user_file "/usr/local/nginx/pass"; #认证密码文件
location / {
root $DocumentRoot;
index index.html index.htm;
}
}
}
EOF
#生成密码文件,创建用户及密码
read -p "认证用户:" Cert_User
read -p "认证密码:" Cert_Pwd
YUM "httpd-tools"
YUM expect
expect << EOF
spawn htpasswd -c /usr/local/nginx/pass $Cert_User
expect ":" {send "$Cert_Pwd\r"}
expect ":" {send "$Cert_Pwd\r"}
expect "#" {send "exit\r"}
EOF
/usr/local/nginx/sbin/nginx -s reload #重启
cecho 36 "配置成功"
}

#基于域名的虚拟主机
add_domain(){
read -p "域名:" Domain
read -p "网页文件根目录:" DocumentRoot
MKDIR /usr/local/nginx/$DocumentRoot
echo "$Domain TEST" > /usr/local/nginx/$DocumentRoot/index.html #创建测试页
#添加配置文件
sed -i '$d' /usr/local/nginx/conf/nginx.conf
cat >> /usr/local/nginx/conf/nginx.conf <<EOF
server {
listen 80;
server_name $Domain;
location / {
root $DocumentRoot;
index index.html index.htm;
}
}
}
EOF
/usr/local/nginx/sbin/nginx -s reload #重启
cecho 36 "$Domain添加成功"
}

#SSL虚拟主机
SSL(){
#生成私钥与证书
cecho 32 "生成私钥和证书"
cd $Install_Path/conf
openssl genrsa > cert.key #不能导入黑洞
openssl req -new -x509 -key cert.key -subj "/CN=common" >cert.pem

#修改配置文件
tmp=`sed -n '/# HTTPS server/=' $Nginx_Conf` #找到HTTPS server的行(96)
line_begin=$[tmp+2]
line_end=$[line_begin+17]
line_domain=$[tmp+4] #修改域名的行
sed -i "${line_begin},${line_end}s/#//" $Nginx_Conf #去掉注释
sed -i "${line_domain}c server_name $Domain_Name;" $Nginx_Conf #修改域名
/usr/local/nginx/sbin/nginx -s reload #重启
cecho 36 "SSL配置成功"
}

#帮助信息
Help(){
cat << EOF
Nginx_Service version 1.1.0
Usage: Nginx_Service [-hNS]
=======================================================================
optional arguments:
-h 提供帮助信息
-N 安装nginx
-S 配置SSL加密
EXAMPLE:
bash Nginx_Service -S
EOF
}

#############################主程序#############################
clear

[ $# -eq 0 ] && Help
while getopts :hNS ARGS
do
case $ARGS in
h)
Help;;
S)
SSL;;
\?)
cecho 31 "Invalid option:bash `basename $0` [-h]"
esac
done