#!/bin/bash

# 定义全局变量
NGINX_VERSION="1.26.2"
INSTALL_DIR="/usr/local/nginx"
SOURCE_URL="http://nginx.org/download/nginx-${NGINX_VERSION}.tar.gz"
TEMP_DIR=$(mktemp -d)
CPU_CORES=$(grep -c ^processor /proc/cpuinfo)
SYSTEM_TYPE=""
SERVICE_FILE="/etc/systemd/system/nginx.service"

# 检测系统类型
detect_system() {
    if [ -f /etc/redhat-release ]; then
        SYSTEM_TYPE="centos"
    elif [ -f /etc/lsb-release ]; then
        SYSTEM_TYPE="ubuntu"
    else
        echo "不支持的系统类型"
        exit 1
    fi
}

# 安装依赖
install_dependencies() {
    echo "安装系统依赖..."
    if [ "$SYSTEM_TYPE" = "centos" ]; then
        yum install -y wget gcc make pcre-devel zlib-devel openssl-devel
    else
        apt-get update
        apt-get install -y wget gcc make libpcre3-dev zlib1g-dev libssl-dev
    fi
    [ $? -eq 0 ] || { echo "依赖安装失败"; exit 1; }
}

# 下载源码
download_nginx() {
    echo "下载Nginx源码..."
    wget -q -P "$TEMP_DIR" "$SOURCE_URL" || { echo "下载失败"; exit 1; }
    tar -xzf "${TEMP_DIR}/nginx-${NGINX_VERSION}.tar.gz" -C "$TEMP_DIR"
}

# 编译安装
compile_install() {
    echo "开始编译安装..."
    cd "${TEMP_DIR}/nginx-${NGINX_VERSION}" || exit 1
    
    ./configure \
        --prefix=${INSTALL_DIR} \
        --sbin-path=${INSTALL_DIR}/sbin/nginx \
        --conf-path=${INSTALL_DIR}/conf/nginx.conf \
        --pid-path=${INSTALL_DIR}/logs/nginx.pid \
        --with-http_ssl_module \
        --with-http_v2_module \
        --with-http_realip_module \
        --with-threads \
        --with-http_gzip_static_module
    
    make -j "$CPU_CORES"
    make install
    [ $? -eq 0 ] || { echo "编译安装失败"; exit 1; }
}

# 创建systemd服务
create_service() {
    echo "创建系统服务..."
    cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=network.target

[Service]
Type=forking
PIDFile=${INSTALL_DIR}/logs/nginx.pid
ExecStartPre=${INSTALL_DIR}/sbin/nginx -t
ExecStart=${INSTALL_DIR}/sbin/nginx
ExecReload=${INSTALL_DIR}/sbin/nginx -s reload
ExecStop=${INSTALL_DIR}/sbin/nginx -s quit
PrivateTmp=true
Restart=on-failure
TimeoutStopSec=10

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
}

# 设置环境变量
set_env() {
    echo "export PATH=${INSTALL_DIR}/sbin:\$PATH" > /etc/profile.d/nginx.sh
    source /etc/profile.d/nginx.sh
}

# 完成提示
show_result() {
    echo ""
    echo "Nginx ${NGINX_VERSION} 安装完成！"
    echo "安装目录：${INSTALL_DIR}"
    echo "服务管理：systemctl [start|stop|restart|status] nginx"
    echo ""
    echo "验证安装：curl -I http://localhost"
    echo ""
}

# 主函数
main() {
    # 检测root权限
    [ "$(id -u)" -ne 0 ] && { echo "请使用root权限执行"; exit 1; }
    
    detect_system
    install_dependencies
    download_nginx
    compile_install
    create_service
    set_env
    
    # 启动服务
    systemctl enable nginx
    systemctl start nginx
    
    show_result
    rm -rf "$TEMP_DIR"
}

main "$@"
