#encoding: utf-8
#!/bin/bash

user=`whoami`
localPwd="$( cd "$( dirname "$0"   )" && pwd   )"

sudoCmd=""
[ "$user" != "root" ] && sudoCmd="sudo " && echo "非root用户，使用免密sudo命令执行。"
appName="nginx-1.23.1.tar.gz"
appNamePrefix="nginx-1.23.1"
installDir="/opt/third/nginx"

function echo_info {
  echo -e "\e[32m`printf '%-20s' "[install_nginx]"`\e[0m - $1"
}
function echo_warn {
  echo -e "\e[31m`printf '%-20s' "[install_nginx]"`\e[0m - $1"
}

function main() {
  echo_info "install gcc openssl"
  $sudoCmd yum install gcc gcc-c++ make automake autoconf pcre pcre-devel zlib zlib-devel openssl openssl-devel libtool -y >/dev/null
  echo_info "check configureFile and installFile"
  [ -f ${localPwd}/${appName} ] && installFile="${localPwd}/$appName"
  [ -z "$installFile" ] && [ -f ${localPwd}/../${appName} ] && installFile="${localPwd}/../${appName}"
  [ -z "$installFile" ] && echo_warn "no ${appName}" && exit 1
  [ ! -f ${localPwd}/services/nginx.service ] && echo_warn "no nginx.service" && exit 1
  [ ! -f ${localPwd}/conf/nginx.conf ] && echo_warn "no nginx.conf" && exit 1
  [ ! -f ${localPwd}/conf/shuqi.conf ] && echo_warn "shuqi.conf" && exit 1
  echo_info "start configure"
  $sudoCmd tar xzf ${installFile} -C ${localPwd}
	$sudoCmd mkdir -p /opt/third/nginx/modules
	$sudoCmd rsync -a ${localPwd}/${appNamePrefix}/headers-more-nginx-module-0.34 /opt/third/nginx/modules/
  cd ${localPwd}/${appNamePrefix}
  ./configure --prefix=$installDir --with-http_ssl_module \
              --with-http_v2_module --with-http_sub_module --with-http_gunzip_module \
              --with-http_gzip_static_module --with-http_random_index_module --with-pcre \
              --with-pcre-jit --with-stream=dynamic --with-stream_ssl_module \
              --add-module=/opt/third/nginx/modules/headers-more-nginx-module-0.34 >/dev/null
  [ $? -ne 0 ] && echo_warn "configure for nginx has error.Stop it." && exit 1
  echo_info "start make install for nginx"
  make >/dev/null 2>&1 && make install >/dev/null 2>&1
  [ $? -ne 0 ] && echo_warn "make for nginx has error.Stop it." && exit 1
  echo_info "create dir [/data/nginx/logs] for nginx's log"
  mkdir -p /data/nginx/logs 
  [ $? -ne 0 ] && echo_warn "create dir[/data/nginx/logs] for nginx has error.Stop it. "  && exit 1
  cd ${localPwd} && rm -rf ${localPwd}/${appNamePrefix}
  mkdir -p ${installDir}/conf/vhosts
  echo_info "copy configFile for nginx"
  \cp ${localPwd}/conf/nginx.conf ${installDir}/conf/nginx.conf
  \cp ${localPwd}/conf/shuqi.conf ${installDir}/conf/vhosts/
  echo_info "create nginx.service for daemon."
  ${sudoCmd} \cp ${localPwd}/services/nginx.service /usr/lib/systemd/system/
  ${sudoCmd} systemctl daemon-reload
  ${sudoCmd} systemctl enable nginx.service
  ${sudoCmd} systemctl start nginx.service
  echo_info "End."
}
main
