#!/bin/bash

# nginx配置检查和修复脚本

echo "🌐 检查和修复nginx配置..."

# 检查nginx是否安装
if ! command -v nginx &> /dev/null; then
    echo "❌ nginx未安装，正在安装..."
    sudo apt update
    sudo apt install nginx -y
fi

# 检查nginx配置文件
NGINX_CONFIG="/etc/nginx/sites-available/ad.ningmuyun.com"
NGINX_ENABLED="/etc/nginx/sites-enabled/ad.ningmuyun.com"

echo "📁 检查nginx配置文件..."

if [ ! -f "$NGINX_CONFIG" ]; then
    echo "❌ nginx配置文件不存在，正在创建..."
    
    # 创建nginx配置
    sudo tee "$NGINX_CONFIG" > /dev/null << 'EOF'
server {
    listen 443 ssl http2;
    server_name ad.ningmuyun.com;
    
    # SSL证书配置（需要替换为实际的证书路径）
    ssl_certificate /etc/ssl/certs/ad.ningmuyun.com.crt;
    ssl_certificate_key /etc/ssl/private/ad.ningmuyun.com.key;
    
    # 如果SSL证书不存在，使用自签名证书（仅用于测试）
    # ssl_certificate /etc/ssl/certs/nginx-selfsigned.crt;
    # ssl_certificate_key /etc/ssl/private/nginx-selfsigned.key;
    
    # SSL配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    
    # 前端静态文件
    location /insurance/ {
        alias /var/www/insurance-admin-system/dist/;
        try_files $uri $uri/ /insurance/index.html;
        
        # 静态资源缓存
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
        }
    }
    
    # 后端API代理
    location /insurance/api/ {
        proxy_pass http://127.0.0.1:3000/api/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
        
        # 超时设置
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        # CORS headers
        add_header Access-Control-Allow-Origin https://ad.ningmuyun.com;
        add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
        add_header Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With";
        add_header Access-Control-Allow-Credentials true;
        
        # 处理预检请求
        if ($request_method = 'OPTIONS') {
            add_header Access-Control-Allow-Origin https://ad.ningmuyun.com;
            add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
            add_header Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With";
            add_header Access-Control-Allow-Credentials true;
            add_header Content-Length 0;
            add_header Content-Type text/plain;
            return 204;
        }
    }
    
    # 健康检查
    location /health {
        proxy_pass http://127.0.0.1:3000/health;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

# HTTP重定向到HTTPS
server {
    listen 80;
    server_name ad.ningmuyun.com;
    return 301 https://$server_name$request_uri;
}
EOF
    
    echo "✅ nginx配置文件已创建"
else
    echo "✅ nginx配置文件已存在"
fi

# 启用站点
if [ ! -L "$NGINX_ENABLED" ]; then
    echo "🔗 启用nginx站点..."
    sudo ln -sf "$NGINX_CONFIG" "$NGINX_ENABLED"
    echo "✅ nginx站点已启用"
else
    echo "✅ nginx站点已启用"
fi

# 检查前端目录
if [ ! -d "/var/www/insurance-admin-system/dist" ]; then
    echo "⚠️  前端目录不存在，创建目录..."
    sudo mkdir -p /var/www/insurance-admin-system/dist
    sudo chown -R www-data:www-data /var/www/insurance-admin-system
    echo "✅ 前端目录已创建"
fi

# 测试nginx配置
echo "🧪 测试nginx配置..."
if sudo nginx -t; then
    echo "✅ nginx配置测试通过"
    
    # 重新加载nginx
    echo "🔄 重新加载nginx..."
    sudo systemctl reload nginx
    
    # 检查nginx状态
    echo "📊 nginx状态:"
    sudo systemctl status nginx --no-pager
    
else
    echo "❌ nginx配置测试失败"
    exit 1
fi

echo ""
echo "✅ nginx配置检查和修复完成！"
echo "📋 配置信息："
echo "   配置文件: $NGINX_CONFIG"
echo "   启用链接: $NGINX_ENABLED"
echo "   前端目录: /var/www/insurance-admin-system/dist"
echo "   API代理: /insurance/api/ → http://127.0.0.1:3000/api/"
