#!/bin/bash

# 脚本信息配置
NGINX_VERSION="1.26.2"
DOWNLOAD_URL="http://nginx.org/download/nginx-${NGINX_VERSION}.tar.gz"
DOWNLOAD_DIR="./download"
INSTALL_DIR="/usr/local/nginx"
CONFIG_DIR="/etc/nginx"
HTML_DIR="/usr/share/nginx/html"
BACKUP_DIR="${HOME}/nginx_backup"
LOG_FILE="./nginx_install.log"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m'

# 初始化环境
init_env() {
    [ ! -d "$DOWNLOAD_DIR" ] && mkdir -p "$DOWNLOAD_DIR"
    [ ! -d "$BACKUP_DIR" ] && mkdir -p "$BACKUP_DIR"
    touch "$LOG_FILE"
}

# 日志记录函数
log() {
    echo -e "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

# 检查root权限
check_root() {
    if [ "$(id -u)" != "0" ]; then
        log "${RED}错误：该脚本需要root权限执行${NC}"
        exit 1
    fi
}

# 检测系统类型
detect_os() {
    if [ -f /etc/redhat-release ]; then
        OS="centos"
        PCRE_DEVEL="pcre-devel"
        OPENSSL_DEVEL="openssl-devel"
    elif [ -f /etc/lsb-release ]; then
        OS="ubuntu"
        PCRE_DEVEL="libpcre3-dev"
        OPENSSL_DEVEL="libssl-dev"
    else
        log "${RED}不支持的操作系统${NC}"
        exit 1
    fi
}

# 安装依赖
install_deps() {
    log "${YELLOW}正在安装依赖包...${NC}"
    
    # 等待apt锁释放（仅Ubuntu）
    if [ "$OS" == "ubuntu" ]; then
        while fuser /var/lib/dpkg/lock-frontend >/dev/null 2>&1 ; do
            log "${YELLOW}检测到apt锁被占用，等待释放...${NC}"
            sleep 5
        done
    fi

    if [ "$OS" == "centos" ]; then
        yum install -y gcc make wget tar $PCRE_DEVEL $OPENSSL_DEVEL zlib-devel >> "$LOG_FILE" 2>&1 || {
            log "${RED}依赖安装失败！${NC}"
            exit 1
        }
    else
        apt-get update >> "$LOG_FILE" 2>&1
        apt-get install -y build-essential wget tar $PCRE_DEVEL $OPENSSL_DEVEL zlib1g-dev >> "$LOG_FILE" 2>&1 || {
            log "${RED}依赖安装失败！${NC}"
            exit 1
        }
    fi
}

# 下载源码
download_nginx() {
    local filename="nginx-${NGINX_VERSION}.tar.gz"
    if [ ! -f "${DOWNLOAD_DIR}/${filename}" ]; then
        log "${YELLOW}正在下载Nginx源码包...${NC}"
        wget -P "$DOWNLOAD_DIR" "$DOWNLOAD_URL" >> "$LOG_FILE" 2>&1 || {
            log "${RED}下载失败，请检查网络连接${NC}"
            exit 1
        }
    else
        log "${GREEN}发现本地缓存源码包，跳过下载${NC}"
    fi
}

# 编译安装
compile_install() {
    log "${YELLOW}开始编译安装Nginx...${NC}"
    
    # 解压源码
    tar zxf "${DOWNLOAD_DIR}/nginx-${NGINX_VERSION}.tar.gz" -C "$DOWNLOAD_DIR" >> "$LOG_FILE" 2>&1 || {
        log "${RED}解压源码包失败！${NC}"
        exit 1
    }
    cd "${DOWNLOAD_DIR}/nginx-${NGINX_VERSION}" || exit 1

    # 配置编译参数
    ./configure \
        --prefix="${INSTALL_DIR}" \
        --sbin-path="${INSTALL_DIR}/sbin/nginx" \
        --conf-path="${CONFIG_DIR}/nginx.conf" \
        --http-client-body-temp-path=/var/cache/nginx/client_temp \
        --http-proxy-temp-path=/var/cache/nginx/proxy_temp \
        --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp \
        --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp \
        --http-scgi-temp-path=/var/cache/nginx/scgi_temp \
        --pid-path=/var/run/nginx.pid \
        --lock-path=/var/run/nginx.lock \
        --error-log-path=/var/log/nginx/error.log \
        --http-log-path=/var/log/nginx/access.log \
        --user=nginx \
        --group=nginx \
        --with-http_ssl_module \
        --with-http_v2_module \
        --with-http_realip_module \
        --with-http_gzip_static_module \
        --with-http_stub_status_module \
        --with-stream \
        --with-threads >> "$LOG_FILE" 2>&1

    [ $? -ne 0 ] && { log "${RED}配置阶段失败！${NC}"; exit 1; }

    # 编译并安装
    make -j$(nproc) >> "$LOG_FILE" 2>&1 || { log "${RED}编译失败！${NC}"; exit 1; }
    make install >> "$LOG_FILE" 2>&1 || { log "${RED}安装失败！${NC}"; exit 1; }

    # 验证二进制文件
    if [ ! -f "${INSTALL_DIR}/sbin/nginx" ]; then
        log "${RED}错误：Nginx二进制文件未生成！${NC}"
        exit 1
    fi
}

# 配置系统服务
config_service() {
    log "${YELLOW}配置系统服务...${NC}"
    
    # 创建nginx用户
    if ! id "nginx" &>/dev/null; then
        useradd -s /sbin/nologin -M nginx || {
            log "${RED}创建nginx用户失败！${NC}"
            exit 1
        }
    fi

    # 创建服务文件
    cat > /etc/systemd/system/nginx.service << EOF
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStartPre=${INSTALL_DIR}/sbin/nginx -t
ExecStart=${INSTALL_DIR}/sbin/nginx
ExecReload=${INSTALL_DIR}/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT \$MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

    # 重载服务配置
    systemctl daemon-reload || {
        log "${RED}服务配置重载失败！${NC}"
        exit 1
    }
    systemctl enable nginx >> "$LOG_FILE" 2>&1
}

# 创建目录结构
create_dirs() {
    log "${YELLOW}创建目录并设置权限...${NC}"
    mkdir -p "$HTML_DIR" "$CONFIG_DIR"/conf.d /var/log/nginx /var/cache/nginx || exit 1
    chown -R nginx:nginx /var/log/nginx /var/cache/nginx
    chmod -R 755 /var/log/nginx /var/cache/nginx
}

# 完成安装
complete_installation() {
    systemctl start nginx || {
        log "${RED}服务启动失败！尝试手动启动：${INSTALL_DIR}/sbin/nginx${NC}"
        exit 1
    }
    log "${GREEN}安装完成！${NC}"
    echo -e "${YELLOW}安装信息："
    echo -e "  二进制文件目录: ${INSTALL_DIR}/sbin/nginx"
    echo -e "  配置文件目录: ${CONFIG_DIR}"
    echo -e "  网站根目录: ${HTML_DIR}"
    echo -e "  服务管理命令: systemctl {start|stop|restart|status} nginx${NC}"
}

# 备份配置
backup_config() {
    local timestamp=$(date +%Y%m%d%H%M%S)
    mkdir -p "${BACKUP_DIR}/${timestamp}"
    [ -d "$CONFIG_DIR" ] && cp -a "$CONFIG_DIR" "${BACKUP_DIR}/${timestamp}/"
    [ -d "$HTML_DIR" ] && cp -a "$HTML_DIR" "${BACKUP_DIR}/${timestamp}/"
    log "${GREEN}配置文件已备份至: ${BACKUP_DIR}/${timestamp}${NC}"
}

# 卸载Nginx
uninstall_nginx() {
    read -r -p "是否要备份现有配置？(y/n): " backup_choice
    if [[ "$backup_choice" =~ ^[Yy] ]]; then
        backup_config
    fi

    log "${YELLOW}开始卸载Nginx...${NC}"
    systemctl stop nginx >> "$LOG_FILE" 2>&1
    systemctl disable nginx >> "$LOG_FILE" 2>&1
    rm -f /etc/systemd/system/nginx.service
    userdel nginx >> "$LOG_FILE" 2>&1
    rm -rf "${INSTALL_DIR}" \
           "$CONFIG_DIR" \
           "$HTML_DIR" \
           /var/cache/nginx \
           /var/log/nginx \
           /var/run/nginx.pid \
           /var/run/nginx.lock
    log "${GREEN}Nginx已成功卸载${NC}"
}

# 主菜单
main_menu() {
    echo -e "\n${GREEN}Nginx 管理脚本 v2.0（修复版）${NC}"
    echo "1. 安装 Nginx ${NGINX_VERSION}"
    echo "2. 卸载 Nginx"
    read -r -p "请选择操作 (1/2): " choice

    case $choice in
        1)
            read -r -p "确认安装 Nginx ${NGINX_VERSION}？(y/n): " confirm
            [[ "$confirm" =~ ^[Yy] ]] || exit 0
            check_root
            init_env
            detect_os
            install_deps
            download_nginx
            compile_install
            create_dirs
            config_service
            complete_installation
            ;;
        2)
            read -r -p "确认要卸载 Nginx？(y/n): " confirm
            [[ "$confirm" =~ ^[Yy] ]] || exit 0
            check_root
            uninstall_nginx
            ;;
        *)
            log "${RED}无效的选择${NC}"
            exit 1
            ;;
    esac
}

# 执行主程序
main_menu
