#!/bin/bash

# Nginx优化脚本
# 功能：自动开启nginx，配置/data/为默认下载目录，支持递归下载
# 支持系统：Debian, Ubuntu, CentOS, Alibaba Cloud Linux

echo "开始执行Nginx优化脚本..."

# 检测系统类型
detect_system() {
    if [[ -f /etc/debian_version ]]; then
        OS="debian"
        PKGMGR="apt-get"
        NGINX_USER="www-data"
        echo "检测到 Debian/Ubuntu 系统"
    elif grep -qiE 'centos|alibaba|alinux|rocky|almalinux|rhel|fedora|anolis|openeuler|opencloudos|tencentos' /etc/os-release 2>/dev/null || \
         [[ -f /etc/centos-release || -f /etc/alibaba-release || -f /etc/alinux-release || -f /etc/redhat-release || -f /etc/rocky-release || -f /etc/almalinux-release || -f /etc/fedora-release ]]; then
        OS="centos"
        if command -v dnf &> /dev/null; then
            PKGMGR="dnf"
        else
            PKGMGR="yum"
        fi
        NGINX_USER="nginx"
        echo "检测到 CentOS/Alibaba Cloud Linux 系统"
    else
        echo "不支持该系统"
        exit 1
    fi
}

# 检查并安装nginx
install_nginx() {
    if ! command -v nginx &> /dev/null; then
        echo "Nginx未安装，开始安装..."
        if [[ $OS == "debian" ]]; then
            $PKGMGR update -y
            $PKGMGR install -y nginx wget curl
        else
            $PKGMGR install -y epel-release
            $PKGMGR install -y nginx wget curl
        fi
        if [ $? -ne 0 ]; then
            echo "Nginx安装失败，请检查网络连接"
            exit 1
        fi
        echo "Nginx安装成功"
    else
        echo "Nginx已安装"
    fi
}

# 配置nginx
configure_nginx() {
    echo "配置Nginx..."
    
    # 创建必要的目录
    mkdir -p /etc/nginx/sites-enabled /etc/nginx/conf.d /var/log/nginx /var/lib/nginx/body /var/lib/nginx/fastcgi
    
    # 备份原始配置文件
    if [[ -f /etc/nginx/nginx.conf ]]; then
        cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak
    fi
    
    # 写入主配置
    cat > /etc/nginx/nginx.conf << EOF
user $NGINX_USER;
worker_processes auto;
pid /var/run/nginx.pid;
events { worker_connections 1024; }
http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    sendfile on;
    keepalive_timeout 65;
    client_max_body_size 0;
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}
EOF
    
    # 写入站点配置
    if [[ $OS == "debian" ]]; then
        CONFIG_PATH="/etc/nginx/sites-available/default"
        ln -sf /etc/nginx/sites-available/default /etc/nginx/sites-enabled/default 2>/dev/null || true
    else
        CONFIG_PATH="/etc/nginx/conf.d/default.conf"
    fi
    
    cat > $CONFIG_PATH << 'EOF'
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /data;

    index index.html index.htm;

    server_name _;

    location / {
        try_files $uri $uri/ =404;
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
        charset utf-8;
        
        if ($request_filename ~* ^.*?\.(txt|doc|pdf|rar|gz|zip|docx|exe|xlsx|ppt|pptx|mp4|mp3|avi|mkv|mov|flv|wmv|wav|flac|aac|iso|img)$) {
            add_header Content-Disposition attachment;
        }
        
        index none;
    }
}
EOF
}

# 检查配置是否正确
check_config() {
    echo "检查Nginx配置..."
    nginx -t
    if [ $? -ne 0 ]; then
        echo "Nginx配置错误，恢复原始配置"
        if [[ -f /etc/nginx/nginx.conf.bak ]]; then
            cp /etc/nginx/nginx.conf.bak /etc/nginx/nginx.conf
        fi
        exit 1
    fi
}

# 设置权限
set_permissions() {
    echo "设置权限..."
    mkdir -p /data
    chown -R $NGINX_USER:$NGINX_USER /data
    find /data -type d -exec chmod 2755 {} +
    find /data -type f -exec chmod 644 {} +
    if command -v setfacl &>/dev/null; then
        setfacl -R -m u:$NGINX_USER:rwx /data 2>/dev/null
        setfacl -d -m u:$NGINX_USER:rwx /data 2>/dev/null
        setfacl -d -m g::r-x /data 2>/dev/null
        setfacl -d -m o::r-x /data 2>/dev/null
    fi
    
    # CentOS SELinux 兼容处理
    if [[ $OS == "centos" ]]; then
        setsebool -P httpd_read_user_content on 2>/dev/null || true
        chcon -R -t httpd_sys_content_t /data 2>/dev/null || true
    fi
}

# 启动并启用nginx服务
start_service() {
    echo "启动Nginx服务..."
    systemctl stop nginx 2>/dev/null || true
    systemctl start nginx
    systemctl enable nginx
    
    # 检查服务状态
    echo "检查Nginx服务状态..."
    systemctl status nginx --no-pager
    
    # 获取服务器IP
    SERVER_IP=$(curl -s icanhazip.com 2>/dev/null || hostname -I | awk '{print $1}')
    
    echo ""
    echo "=== Nginx优化脚本执行完成 ==="
    echo "默认下载目录：/data/"
    echo "放入此目录的文件和文件夹都会自动支持递归下载，无需手动改权限"
    echo "🌐 访问地址：http://$SERVER_IP/"
    echo "使用方法：wget -r --no-parent http://服务器IP/目录名/"
    echo ""
}

# 执行
detect_system
install_nginx
configure_nginx
check_config
set_permissions
start_service
