#!/bin/bash
# 2024-12

[ $(id -u) -eq 0 ] || echo "需要用root用户操作!"
[ $(id -u) -eq 0 ] || exit 4;

#获取脚本根目录，并设为只读
readonly INITDIR=$(cd $(dirname $0); dirname "$PWD")
source $INITDIR/conf/init.conf
STAMP=`date -d today +"%Y%m%d%H%M%S"`

if [ ! -d "/opt/nginx/" ]; then
  echo "检测无/opt/nginx/目录"
else
  pkill -f -9 nginx
  mv /opt/nginx/ /opt/nginx_$STAMP
  echo "检测已存在/opt/nginx/目录，并已备份"
fi

#安装组件支持库
yum install -y make cmake pcre pcre-devel zlib zlib-devel openssl openssl-devel
echo "nginx所需组件安装完成"

tar -xzf $INITDIR/file/nginx/nginx-1.20.0.tar.gz -C /tmp/
echo "nginx解压完成"

cd /tmp/nginx-1.20.0/ ; ./configure --prefix=/opt/nginx --with-http_ssl_module --with-http_v2_module --with-http_gzip_static_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'
cd /tmp/nginx-1.20.0/ ; make && make install
echo "nginx编译完成"

#配置
\cp -rf $INITDIR/file/nginx/nginx.conf /opt/nginx/conf/
if [ "$SSL_HTTPS" == "true" ]; then
  \cp -rf $INITDIR/file/nginx/ssl.conf /opt/nginx/conf/
  \cp -rf $INITDIR/file/nginx/port_ssl_443.conf /opt/nginx/conf/
  sed -i "s@CERTIFICATE_PATH@$CERTIFICATE_PATH@g" /opt/nginx/conf/ssl.conf
  sed -i "s@CERTIFICATE_KEY_PATH@$CERTIFICATE_KEY_PATH@g" /opt/nginx/conf/ssl.conf
  sed -i "s@FASTDFS_IP@$FASTDFS_IP@g" /opt/nginx/conf/port_ssl_443.conf
  sed -i "s@VIDEO_IP@$VIDEO_IP@g" /opt/nginx/conf/port_ssl_443.conf
  sed -i "s@#https443#@@g" /opt/nginx/conf/nginx.conf
  if [[ "$WEB_IP" == "$VIDEO_IP" ]]; then
    \cp -rf $INITDIR/file/nginx/port_ssl_797x.conf /opt/nginx/conf/
    \cp -rf $INITDIR/file/nginx/port_8799.conf /opt/nginx/conf/
    sed -i "s@#https797x#@@g" /opt/nginx/conf/nginx.conf
    sed -i "s@#http8799#@@g" /opt/nginx/conf/nginx.conf
    echo "nginx配置完成（https + video）"
  else
    echo "nginx配置完成（https）"
  fi
else
  \cp -rf $INITDIR/file/nginx/port_80.conf /opt/nginx/conf/
  sed -i "s@#http80#@@g" /opt/nginx/conf/nginx.conf
  if [[ "$WEB_IP" == "$VIDEO_IP" ]]; then
    \cp -rf $INITDIR/file/nginx/port_8799.conf /opt/nginx/conf/

    sed -i "s@#http8799#@@g" /opt/nginx/conf/nginx.conf
    echo "nginx配置完成（http + video）"
  else
    echo "nginx配置完成（http）"
  fi
fi
sed -i "s@WEB_URL@$WEB_URL@g" /opt/nginx/conf/nginx.conf /opt/nginx/conf/port_*.conf
echo "nginx通用配置完成"
\rm -rf /tmp/nginx-1.20.0/
echo "nginx安装完成。"


sed -i '\/opt\/nginx\/sbin\/nginx/d' /etc/rc.d/rc.local
echo '/opt/nginx/sbin/nginx' >> /etc/rc.d/rc.local

/opt/nginx/sbin/nginx

