#!/bin/bash
#auto install Nginx virtual Hosts
#by author ale
#2019-4-30 15:17:57

#define variables
NGINX_CONF="/usr/local/nginx/conf"
NGINX_MAKE="--user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module"
NGINX_SBIN="/usr/local/nginx/sbin/nginx"

NGINX_INSTALL(){
#Install Nginx server
NGINX_FILE=nginx-1.12.2.tar.gz
NGINX_DIR=`echo $NGINX_FILE|sed 's/.tar*.*//g'`
if [ ! -e /usr/local/nginx -a ! -e /etc/nginx ];then
    pkill nginx
    wget -c http://nginx.org/download/$NGINX_FILE
    yum install pcre pcre-devel openssl openssl-devel -y
    rm -rf $NGINX_DIR;tar xzf $NGINX_FILE
    cd $NGINX_DIR;useradd www;./configure $NGINX_MAKE
    make &&make install
    grep -vE "#|^$" $NGINX_CONF/nginx.conf >$NGINX_CONF/nginx.conf.swp
    \mv $NGINX_CONF/nginx.conf.swp $NGINX_CONF/nginx.conf
    sed -i '/server/,$d' $NGINX_CONF/nginx.conf
    #echo "}" >>$NGINX_CONF/nginx.conf
    cd ../
fi
}

NGINX_CONFIG(){
#config nginx vhosts
grep "include domains" $NGINX_CONF/nginx.conf >>/dev/null 2>&1
if [ $? -ne 0 ];then
    #sed -i '$d' $NGINX_CONF/nginx.conf
    echo -e "\ninclude domains/*;\n}">>$NGINX_CONF/nginx.conf
    mkdir -p $NGINX_CONF/domains/
fi
VHOSTS=$1
ls $NGINX_CONF/domains/$VHOSTS >>/dev/null 2>&1
if [ $? -ne 0 ];then
    #cp -r xxx.good.com $NGINX_CONF/domains/$VHOSTS
    #sed -i "s/xxx/$VHOSTS/g" $NGINX_CONF/domains/$VHOSTS
    cat>$NGINX_CONF/domains/$VHOSTS<<EOF
#vhost server $VHOSTS 
    server {
        listen       80;
        server_name  $VHOSTS;
        location / {
            root   /data/www/$VHOSTS/;
            index  index.html index.htm;
        }
      }
EOF
    mkdir -p /data/www/$VHOSTS/
    cat>/data/www/$VHOSTS/index.html<<EOF
    <html>
    <h1><center>The First Test Nginx page.</center></h1>
    <hr color="red">
    <h2><center>$VHOSTS</center></h2>
    </html>
EOF
    echo -e "033[32mThe $VHOSTS Config success,you can to access http://$VHOSTS/\033[0m"
    NUM=`ps -ef|grep nginx|grep -v grep|grep -v auto|wc -l`
    $NGINX_SBIN -t >>/dev/null 2>&1
    if [ $? -eq 0 -a $NUM -eq 0 ];then
        $NGINX_SBIN
    else
        $NGINX_SBIN -t >>/dev/null 2>&1
        if [ $? -eq 0 ];then
            $NGINX_SBIN -s reload
        fi
    fi
else
    echo -e "\033[32mThe $VHOSTS has been config,please exit.\033[0m"
fi
}

if [ -z $1 ];then
    echo -e "\033[32m------------\033[0m"
    echo -e "\033[32mPlease enter sh $0 xx.ale.com\033[0m"
    exit 0
fi

NGINX_INSTALL
NGINX_CONFIG $1