#!/bin/bash

# 脚本功能：修改Nginx配置以获取真实用户IP
# 适用系统：CentOS 7+, Ubuntu 16.04+, Debian 9+
# 注意：请以root权限运行

echo "开始修改Nginx配置以获取真实用户IP..."

# 查找Nginx配置文件
NGINX_CONF=""
if [ -f "/www/server/nginx/conf/nginx.conf" ]; then
    NGINX_CONF="/www/server/nginx/conf/nginx.conf"
elif [ -f "/etc/nginx/nginx.conf" ]; then
    NGINX_CONF="/etc/nginx/nginx.conf"
elif [ -f "/usr/local/nginx/conf/nginx.conf" ]; then
    NGINX_CONF="/usr/local/nginx/conf/nginx.conf"
else
    echo "错误: 找不到Nginx配置文件"
    exit 1
fi

echo "找到Nginx配置文件: $NGINX_CONF"

# 备份原始配置文件
BACKUP_FILE="${NGINX_CONF}.bak.$(date +%Y%m%d%H%M%S)"
cp "$NGINX_CONF" "$BACKUP_FILE"
echo "已备份配置文件到: $BACKUP_FILE"

# 检查是否已存在相关配置
if grep -q "set_real_ip_from" "$NGINX_CONF" || grep -q "real_ip_header" "$NGINX_CONF"; then
    echo "检测到已存在真实IP配置，将先移除现有配置..."
    # 移除现有配置
    sed -i '/set_real_ip_from/d' "$NGINX_CONF"
    sed -i '/real_ip_header/d' "$NGINX_CONF"
fi

# 在keepalive_timeout 60;后添加配置
if grep -q "keepalive_timeout 60;" "$NGINX_CONF"; then
    sed -i '/keepalive_timeout 60;/a\    set_real_ip_from 0.0.0.0/0;\n    real_ip_header X-Forwarded-For;' "$NGINX_CONF"
    echo "已在keepalive_timeout 60;后添加真实IP配置"
else
    echo "未找到keepalive_timeout 60;配置，尝试在http块中添加..."
    # 尝试在http块中添加
    if grep -q "http {" "$NGINX_CONF"; then
        sed -i '/http {/a\    set_real_ip_from 0.0.0.0/0;\n    real_ip_header X-Forwarded-For;' "$NGINX_CONF"
        echo "已在http块中添加真实IP配置"
    else
        echo "错误: 无法找到合适的位置添加配置"
        echo "请手动在Nginx配置文件的http块中添加以下内容:"
        echo "    set_real_ip_from 0.0.0.0/0;"
        echo "    real_ip_header X-Forwarded-For;"
        exit 1
    fi
fi

# 检查Nginx配置语法
echo "检查Nginx配置语法..."
if nginx -t; then
    echo "Nginx配置语法检查通过"
    
    # 重新加载Nginx配置
    if pgrep -x "nginx" > /dev/null; then
        echo "重新加载Nginx配置..."
        nginx -s reload
        if [ $? -eq 0 ]; then
            echo "Nginx配置重新加载成功"
            echo "现在Nginx将能够获取到用户的真实IP地址"
        else
            echo "Nginx配置重新加载失败"
        fi
    else
        echo "Nginx未运行，配置将在下次启动时生效"
    fi
else
    echo "Nginx配置语法检查失败，已恢复备份文件"
    cp "$BACKUP_FILE" "$NGINX_CONF"
    echo "请手动检查Nginx配置"
    exit 1
fi

echo "操作完成！"
echo "Nginx配置已修改，现在可以获取到用户的真实IP地址。"