#!/bin/bash

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

# 检查是否为 root 用户
if [ "$EUID" -ne 0 ]; then
  echo -e "${RED}请使用 root 权限运行此脚本 (sudo ./optimize_nginx.sh)${NC}"
  exit 1
fi

echo -e "${YELLOW}=== Nginx 自动优化与配置脚本 (支持自定义端口) ===${NC}"

# =========================================================
# 1. 用户检测逻辑
# =========================================================
NGINX_USER="nginx"
if id "nginx" &>/dev/null; then
    echo -e "检测到系统用户: ${GREEN}nginx${NC}"
    NGINX_USER="nginx"
elif id "www-data" &>/dev/null; then
    echo -e "未找到 nginx 用户，检测到系统用户: ${GREEN}www-data${NC}"
    NGINX_USER="www-data"
else
    echo -e "${RED}错误: 系统中既没有 nginx 用户也没有 www-data 用户。${NC}"
    echo "请先安装 nginx 或手动创建用户。"
    exit 1
fi

# =========================================================
# 2. 交互输入：端口与配置文件选择
# =========================================================

# --- 获取端口 ---
echo -e "\n请输入 Nginx 监听端口 [直接回车默认为 8080]:"
read -p "端口: " INPUT_PORT
LISTEN_PORT=${INPUT_PORT:-8080} # 如果为空，设为 8080

# 简单验证端口是否为数字
if ! [[ "$LISTEN_PORT" =~ ^[0-9]+$ ]]; then
    echo -e "${RED}错误: 端口必须是数字。${NC}"
    exit 1
fi
echo -e "将使用端口: ${GREEN}$LISTEN_PORT${NC}"

# --- 获取要生成的配置 ---
CONF_D_DIR="/etc/nginx/conf.d"
mkdir -p "$CONF_D_DIR"

echo -e "\n请选择要生成的配置文件 (输入名称，空格分隔):"
echo -e "可选项: ${GREEN}bcn${NC} (4617端口), ${GREEN}pcn${NC} (5617端口), ${GREEN}fcn${NC} (6617端口)"
echo -e "示例输入: 'bcn' 或 'bcn pcn' 或 'bcn pcn fcn'"
read -p "请输入: " USER_CHOICE
# 转换为小写
USER_CHOICE=$(echo "$USER_CHOICE" | tr '[:upper:]' '[:lower:]')

# =========================================================
# 3. 写入主配置文件 nginx.conf
# =========================================================
CONF_DIR="/etc/nginx"
MAIN_CONF="$CONF_DIR/nginx.conf"

# 备份原文件
if [ -f "$MAIN_CONF" ]; then
    BACKUP_NAME="$MAIN_CONF.bak.$(date +%F_%T)"
    cp "$MAIN_CONF" "$BACKUP_NAME"
    echo -e "\n已备份原 nginx.conf 至: ${YELLOW}$BACKUP_NAME${NC}"
fi

echo "正在写入优化后的 nginx.conf..."

# 使用 cat << 'EOF' 防止 shell 变量扩展
cat > "$MAIN_CONF" << 'EOF'
user  nginx;
# 自动绑定 CPU 核数，保持 auto
worker_processes  auto;

# [优化1] 提高最大文件打开数 (必须大于 worker_connections)
worker_rlimit_nofile 65535;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;

events {
    # [优化2] Linux 下强制使用 epoll 模式
    use epoll;
    # [优化3] 大幅提高连接数
    worker_connections  16384;
    # [优化4] 允许一个 worker 同时接受多个新连接
    multi_accept on;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    # 日志格式
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    # [优化5] 生产环境建议关闭日志或缓冲写入
    access_log off; 

    sendfile        on;
    # [优化6] 允许把 http response header 和文件的开始放在一个 packet 里发送
    tcp_nopush      on;
    # [优化7] 对 WebSocket 禁用 Nagle 算法，降低延迟
    tcp_nodelay     on;

    keepalive_timeout  65;
    
    # [优化8] 开启 gzip 压缩
    gzip  on;
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    gzip_comp_level 3;
    gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;

    include /etc/nginx/conf.d/*.conf;
}
EOF

# 如果用户是 www-data，修正配置文件中的 user 指令
if [ "$NGINX_USER" == "www-data" ]; then
    sed -i 's/^user  nginx;/user  www-data;/' "$MAIN_CONF"
    echo -e "已将 nginx.conf 运行用户修正为: ${GREEN}www-data${NC}"
fi

# =========================================================
# 4. 生成子配置文件函数 (使用占位符 {{PORT}})
# =========================================================

# --- 函数：写入 bcn.conf ---
write_bcn() {
    FILE="$CONF_D_DIR/bcn.conf"
    echo "正在生成 $FILE (监听端口 $LISTEN_PORT)..."
    cat > "$FILE" << 'EOF'
# ============================================================
# 1. 定义后端长连接池 (性能核心)
# ============================================================
upstream v2ray_backend {
    server 127.0.0.1:4617;
    keepalive 512;
}

# ============================================================
# 2. Server 块定义
# ============================================================

# Domain: www.ctyun.cn
server {
    listen {{PORT}};
    server_name www.ctyun.cn;
    access_log off;

    # --- V2Ray 核心路径 (高性能模式) ---
    location /steaming {
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;
        
        # 使用长连接池
        proxy_pass http://v2ray_backend;

        # [性能优化] 关闭缓冲
        proxy_buffering off;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }

    # --- 伪装路径 (Akamai 隐匿模式) ---
    location / {
        proxy_ssl_server_name on;
        proxy_ssl_name www.akamai.com;
        proxy_pass https://www.akamai.com/;
        
        proxy_set_header Host www.akamai.com;
        proxy_set_header X-Real-IP "";
        proxy_set_header X-Forwarded-For "";
        proxy_set_header X-Forwarded-Proto "";

        proxy_set_header User-Agent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
        proxy_set_header Referer "https://www.akamai.com/";
        proxy_hide_header Via;
        proxy_hide_header X-Powered-By;

        proxy_buffering on;
        sub_filter 'www.akamai.com' 'www.ctyun.cn';
        sub_filter_once off;
    }
}

# Domain: cloud.huawei.com
server {
    listen {{PORT}};
    server_name cloud.huawei.com;
    access_log off;

    location /steaming {
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;
        proxy_pass http://v2ray_backend;
        proxy_buffering off;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }

    location / {
        proxy_ssl_server_name on;
        proxy_ssl_name www.akamai.com;
        proxy_pass https://www.akamai.com/;
        proxy_set_header Host www.akamai.com;
        
        proxy_set_header X-Real-IP "";
        proxy_set_header X-Forwarded-For "";
        proxy_set_header User-Agent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
        proxy_hide_header Via;

        proxy_buffering on;
        sub_filter 'www.akamai.com' 'cloud.huawei.com';
        sub_filter_once off;
    }
}

# Domain: www.qingcloud.com
server {
    listen {{PORT}};
    server_name www.qingcloud.com;
    access_log off;

    location /steaming {
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;
        proxy_pass http://v2ray_backend;
        proxy_buffering off;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }

    location / {
        proxy_ssl_server_name on;
        proxy_ssl_name www.akamai.com;
        proxy_pass https://www.akamai.com/;
        proxy_set_header Host www.akamai.com;
        
        proxy_set_header X-Real-IP "";
        proxy_set_header X-Forwarded-For "";
        proxy_set_header User-Agent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
        proxy_hide_header Via;

        proxy_buffering on;
        sub_filter 'www.akamai.com' 'www.qingcloud.com';
        sub_filter_once off;
    }
}

# Domain: www.cucloud.cn
server {
    listen {{PORT}};
    server_name www.cucloud.cn;
    access_log off;

    location /steaming {
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;
        proxy_pass http://v2ray_backend;
        proxy_buffering off;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }

    location / {
        proxy_ssl_server_name on;
        proxy_ssl_name www.akamai.com;
        proxy_pass https://www.akamai.com/;
        proxy_set_header Host www.akamai.com;
        
        proxy_set_header X-Real-IP "";
        proxy_set_header X-Forwarded-For "";
        proxy_set_header User-Agent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
        proxy_hide_header Via;

        proxy_buffering on;
        sub_filter 'www.akamai.com' 'www.cucloud.cn';
        sub_filter_once off;
    }
}

# Domain: www.aliyun.com
server {
    listen {{PORT}};
    server_name www.aliyun.com;
    access_log off;

    location /steaming {
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;
        proxy_pass http://v2ray_backend;
        proxy_buffering off;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }

    location / {
        proxy_ssl_server_name on;
        proxy_ssl_name www.akamai.com;
        proxy_pass https://www.akamai.com/;
        proxy_set_header Host www.akamai.com;
        
        proxy_set_header X-Real-IP "";
        proxy_set_header X-Forwarded-For "";
        proxy_set_header User-Agent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
        proxy_hide_header Via;

        proxy_buffering on;
        sub_filter 'www.akamai.com' 'www.aliyun.com';
        sub_filter_once off;
    }
}

# Domain: cloud.tencent.com
server {
    listen {{PORT}};
    server_name cloud.tencent.com;
    access_log off;

    location /steaming {
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;
        proxy_pass http://v2ray_backend;
        proxy_buffering off;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }

    location / {
        proxy_ssl_server_name on;
        proxy_ssl_name www.akamai.com;
        proxy_pass https://www.akamai.com/;
        proxy_set_header Host www.akamai.com;
        
        proxy_set_header X-Real-IP "";
        proxy_set_header X-Forwarded-For "";
        proxy_set_header User-Agent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
        proxy_hide_header Via;

        proxy_buffering on;
        sub_filter 'www.akamai.com' 'cloud.tencent.com';
        sub_filter_once off;
    }
}
EOF
    # 替换端口占位符
    sed -i "s/{{PORT}}/$LISTEN_PORT/g" "$FILE"
}

# --- 函数：写入 pcn.conf ---
write_pcn() {
    FILE="$CONF_D_DIR/pcn.conf"
    echo "正在生成 $FILE (监听端口 $LISTEN_PORT)..."
    cat > "$FILE" << 'EOF'
upstream v2ray_backend_5617 {
    server 127.0.0.1:5617;
    keepalive 512;
}

# Domain: www.ucloud.cn
server {
    listen {{PORT}};
    server_name www.ucloud.cn;
    access_log off;

    location /newpath {
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;
        proxy_pass http://v2ray_backend_5617;
        proxy_buffering off;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }

    location / {
        proxy_ssl_server_name on;
        proxy_ssl_name www.akamai.com;
        proxy_pass https://www.akamai.com/;
        proxy_set_header Host www.akamai.com;

        proxy_set_header X-Real-IP "";
        proxy_set_header X-Forwarded-For "";
        proxy_set_header X-Forwarded-Proto "";
        proxy_set_header User-Agent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
        proxy_hide_header Via;
        proxy_hide_header X-Powered-By;

        proxy_buffering on;
        sub_filter 'www.akamai.com' 'www.ucloud.cn';
        sub_filter_once off;
    }
}

# Domain: www.jdcloud.com
server {
    listen {{PORT}};
    server_name www.jdcloud.com;
    access_log off;

    location /newpath {
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;
        proxy_pass http://v2ray_backend_5617;
        proxy_buffering off;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }

    location / {
        proxy_ssl_server_name on;
        proxy_ssl_name www.akamai.com;
        proxy_pass https://www.akamai.com/;
        proxy_set_header Host www.akamai.com;
        
        proxy_set_header X-Real-IP "";
        proxy_set_header X-Forwarded-For "";
        proxy_set_header User-Agent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
        proxy_hide_header Via;

        proxy_buffering on;
        sub_filter 'www.akamai.com' 'www.jdcloud.com';
        sub_filter_once off;
    }
}

# Domain: www.ksyun.com
server {
    listen {{PORT}};
    server_name www.ksyun.com;
    access_log off;

    location /newpath {
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;
        proxy_pass http://v2ray_backend_5617;
        proxy_buffering off;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }

    location / {
        proxy_ssl_server_name on;
        proxy_ssl_name www.akamai.com;
        proxy_pass https://www.akamai.com/;
        proxy_set_header Host www.akamai.com;
        
        proxy_set_header X-Real-IP "";
        proxy_set_header X-Forwarded-For "";
        proxy_set_header User-Agent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
        proxy_hide_header Via;

        proxy_buffering on;
        sub_filter 'www.akamai.com' 'www.ksyun.com';
        sub_filter_once off;
    }
}
EOF
    # 替换端口占位符
    sed -i "s/{{PORT}}/$LISTEN_PORT/g" "$FILE"
}

# --- 函数：写入 fcn.conf ---
write_fcn() {
    FILE="$CONF_D_DIR/fcn.conf"
    echo "正在生成 $FILE (监听端口 $LISTEN_PORT)..."
    cat > "$FILE" << 'EOF'
upstream v2ray_backend_6617 {
    server 127.0.0.1:6617;
    keepalive 512;
}

# Domain: www.alipan.com
server {
    listen {{PORT}};
    server_name www.alipan.com;
    access_log off;

    location /newpath {
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;
        proxy_pass http://v2ray_backend_6617;
        proxy_buffering off;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }

    location / {
        proxy_ssl_server_name on;
        proxy_ssl_name www.akamai.com;
        proxy_pass https://www.akamai.com/;
        proxy_set_header Host www.akamai.com;

        proxy_set_header X-Real-IP "";
        proxy_set_header X-Forwarded-For "";
        proxy_set_header X-Forwarded-Proto "";
        proxy_set_header User-Agent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
        proxy_hide_header Via;
        proxy_hide_header X-Powered-By;

        proxy_buffering on;
        sub_filter 'www.akamai.com' 'www.alipan.com';
        sub_filter_once off;
    }
}

# Domain: www.jianguoyun.com
server {
    listen {{PORT}};
    server_name www.jianguoyun.com;
    access_log off;

    location /newpath {
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;
        proxy_pass http://v2ray_backend_6617;
        proxy_buffering off;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }

    location / {
        proxy_ssl_server_name on;
        proxy_ssl_name www.akamai.com;
        proxy_pass https://www.akamai.com/;
        proxy_set_header Host www.akamai.com;

        proxy_set_header X-Real-IP "";
        proxy_set_header X-Forwarded-For "";
        proxy_set_header User-Agent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
        proxy_hide_header Via;

        proxy_buffering on;
        sub_filter 'www.akamai.com' 'www.jianguoyun.com';
        sub_filter_once off;
    }
}

# Domain: mirrors.163.com
server {
    listen {{PORT}};
    server_name mirrors.163.com;
    access_log off;

    location /newpath {
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;
        proxy_pass http://v2ray_backend_6617;
        proxy_buffering off;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }

    location / {
        proxy_ssl_server_name on;
        proxy_ssl_name www.akamai.com;
        proxy_pass https://www.akamai.com/;
        proxy_set_header Host www.akamai.com;

        proxy_set_header X-Real-IP "";
        proxy_set_header X-Forwarded-For "";
        proxy_set_header User-Agent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
        proxy_hide_header Via;

        proxy_buffering on;
        sub_filter 'www.akamai.com' 'mirrors.163.com';
        sub_filter_once off;
    }
}
EOF
    # 替换端口占位符
    sed -i "s/{{PORT}}/$LISTEN_PORT/g" "$FILE"
}

# --- 处理用户选择 ---

if [[ "$USER_CHOICE" == *"bcn"* ]]; then
    write_bcn
fi

if [[ "$USER_CHOICE" == *"pcn"* ]]; then
    write_pcn
fi

if [[ "$USER_CHOICE" == *"fcn"* ]]; then
    write_fcn
fi

# =========================================================
# 5. 测试与重启
# =========================================================
echo -e "\n${YELLOW}=== 正在测试 Nginx 配置 ===${NC}"

if nginx -t; then
    echo -e "${GREEN}配置测试通过 (Syntax OK)${NC}"
    echo "正在重启 Nginx 服务..."
    
    if systemctl restart nginx; then
        echo -e "${GREEN}Nginx 重启成功!${NC}"
        echo -e "服务状态:"
        systemctl status nginx --no-pager | head -n 5
        echo -e "\n${GREEN}优化完成！${NC} 监听端口: $LISTEN_PORT"
    else
        echo -e "${RED}Nginx 重启失败! 请检查 'systemctl status nginx' 或 error log${NC}"
        exit 1
    fi
else
    echo -e "${RED}配置测试失败! 请检查上述错误信息。${NC}"
    echo "未执行重启操作，以防服务中断。"
    exit 1
fi
