#!/bin/bash

# Nginx + SSL 证书快速配置脚本
# 使用方法: ./setup_ssl.sh <域名> <后端端口> <前端路径> [证书ZIP文件]
# 示例: ./setup_ssl.sh hidim.zhshihe.cn 8090 /data/Hi-Dim/frontend-react/dist hidim.zhshihe.cn_nginx.zip

set -e  # 遇到错误立即退出

DOMAIN=$1
BACKEND_PORT=$2
FRONTEND_PATH=$3
CERT_ZIP=$4

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

# 检查参数
if [ -z "$DOMAIN" ] || [ -z "$BACKEND_PORT" ] || [ -z "$FRONTEND_PATH" ]; then
    echo -e "${RED}❌ 参数错误${NC}"
    echo ""
    echo "使用方法: $0 <域名> <后端端口> <前端路径> [证书ZIP文件]"
    echo ""
    echo "示例:"
    echo "  $0 hidim.zhshihe.cn 8090 /data/Hi-Dim/frontend-react/dist hidim.zhshihe.cn_nginx.zip"
    echo ""
    echo "参数说明:"
    echo "  域名: 您的域名（如 hidim.zhshihe.cn）"
    echo "  后端端口: 后端服务运行的端口（如 8090）"
    echo "  前端路径: 前端构建产物的路径（如 /data/project/frontend/dist）"
    echo "  证书ZIP: （可选）证书 ZIP 文件路径，如果提供会自动安装证书"
    exit 1
fi

echo -e "${GREEN}🔧 开始配置 $DOMAIN ...${NC}"
echo ""

# 1. 安装证书（如果提供了 ZIP 文件）
if [ -n "$CERT_ZIP" ]; then
    if [ ! -f "$CERT_ZIP" ]; then
        echo -e "${RED}❌ 证书文件不存在: $CERT_ZIP${NC}"
        exit 1
    fi
    
    echo -e "${YELLOW}📦 解压证书文件...${NC}"
    TEMP_DIR=$(mktemp -d)
    unzip -q -o "$CERT_ZIP" -d "$TEMP_DIR" || {
        echo -e "${RED}❌ 证书文件解压失败${NC}"
        exit 1
    }
    
    # 查找证书文件
    CERT_DIR=$(find "$TEMP_DIR" -type d -name "*nginx" | head -1)
    if [ -z "$CERT_DIR" ]; then
        echo -e "${RED}❌ 未找到证书目录${NC}"
        exit 1
    fi
    
    # 创建证书目录
    echo -e "${YELLOW}📁 创建证书目录...${NC}"
    sudo mkdir -p /etc/nginx/ssl/$DOMAIN
    
    # 复制证书文件
    CERT_FILE=$(find "$CERT_DIR" -name "*_bundle.crt" -o -name "*_bundle.pem" | head -1)
    KEY_FILE=$(find "$CERT_DIR" -name "*.key" | head -1)
    
    if [ -z "$CERT_FILE" ] || [ -z "$KEY_FILE" ]; then
        echo -e "${RED}❌ 未找到证书文件或私钥文件${NC}"
        exit 1
    fi
    
    sudo cp "$CERT_FILE" /etc/nginx/ssl/$DOMAIN/cert.crt
    sudo cp "$KEY_FILE" /etc/nginx/ssl/$DOMAIN/cert.key
    
    # 设置权限
    sudo chmod 644 /etc/nginx/ssl/$DOMAIN/cert.crt
    sudo chmod 600 /etc/nginx/ssl/$DOMAIN/cert.key
    sudo chown root:root /etc/nginx/ssl/$DOMAIN/*
    
    # 清理临时文件
    rm -rf "$TEMP_DIR"
    
    echo -e "${GREEN}✅ 证书已安装${NC}"
    echo ""
fi

# 2. 检查前端路径
if [ ! -d "$FRONTEND_PATH" ]; then
    echo -e "${YELLOW}⚠️  前端路径不存在: $FRONTEND_PATH${NC}"
    echo -e "${YELLOW}   继续配置，但请确保路径正确${NC}"
    echo ""
fi

# 3. 创建 Nginx 配置
echo -e "${YELLOW}📝 创建 Nginx 配置...${NC}"

# 生成配置文件
sudo tee /etc/nginx/sites-enabled/$DOMAIN > /dev/null <<EOF
# Nginx 配置文件 - $DOMAIN
# 后端端口: $BACKEND_PORT
# 前端路径: $FRONTEND_PATH

# HTTP 服务器 - 自动重定向到HTTPS
server {
    listen 80;
    listen [::]:80;
    server_name $DOMAIN;

    # Let's Encrypt验证目录
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    # 其他所有请求重定向到HTTPS
    location / {
        return 301 https://\$server_name\$request_uri;
    }
}

# HTTPS 服务器
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name $DOMAIN;

    # SSL证书配置
    ssl_certificate /etc/nginx/ssl/$DOMAIN/cert.crt;
    ssl_certificate_key /etc/nginx/ssl/$DOMAIN/cert.key;
    
    # SSL优化配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # 安全头
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

    # 日志
    access_log /var/log/nginx/${DOMAIN}_access.log;
    error_log /var/log/nginx/${DOMAIN}_error.log;

    # 客户端上传大小限制
    client_max_body_size 20M;

    # 前端静态文件
    location / {
        root $FRONTEND_PATH;
        index index.html;
        # 支持前端路由的 history 模式
        try_files \$uri \$uri/ /index.html;
        
        # 静态资源缓存
        location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
        }
    }

    # 后端API
    location /api/ {
        proxy_pass http://localhost:$BACKEND_PORT;
        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 300s;
        proxy_send_timeout 300s;
        proxy_read_timeout 300s;
        
        # CORS headers
        add_header Access-Control-Allow-Origin * always;
        add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;
        add_header Access-Control-Allow-Headers "Authorization, Content-Type" always;
    }

    # 健康检查
    location /health {
        proxy_pass http://localhost:$BACKEND_PORT/health;
        access_log off;
    }

    # API文档（可选）
    location /docs {
        proxy_pass http://localhost:$BACKEND_PORT/docs;
        proxy_set_header Host \$host;
    }
}
EOF

echo -e "${GREEN}✅ 配置文件已创建${NC}"
echo ""

# 4. 测试配置
echo -e "${YELLOW}🧪 测试 Nginx 配置...${NC}"
if sudo nginx -t > /dev/null 2>&1; then
    echo -e "${GREEN}✅ 配置测试通过${NC}"
    echo ""
    
    # 5. 重载 Nginx
    echo -e "${YELLOW}🔄 重载 Nginx...${NC}"
    sudo systemctl reload nginx
    echo -e "${GREEN}✅ Nginx 已重载${NC}"
    echo ""
    
    # 6. 显示配置信息
    echo -e "${GREEN}========================================${NC}"
    echo -e "${GREEN}🎉 配置完成！${NC}"
    echo -e "${GREEN}========================================${NC}"
    echo ""
    echo "域名: $DOMAIN"
    echo "后端端口: $BACKEND_PORT"
    echo "前端路径: $FRONTEND_PATH"
    echo ""
    echo "访问地址:"
    echo "  - HTTPS: https://$DOMAIN"
    echo "  - API: https://$DOMAIN/api"
    echo "  - 文档: https://$DOMAIN/docs"
    echo ""
    
    # 检查证书（如果已安装）
    if [ -f "/etc/nginx/ssl/$DOMAIN/cert.crt" ]; then
        echo "证书信息:"
        sudo openssl x509 -in /etc/nginx/ssl/$DOMAIN/cert.crt -noout -dates -subject 2>/dev/null | sed 's/^/  /'
        echo ""
    fi
    
    echo "配置文件: /etc/nginx/sites-enabled/$DOMAIN"
    echo "证书目录: /etc/nginx/ssl/$DOMAIN/"
    echo "访问日志: /var/log/nginx/${DOMAIN}_access.log"
    echo "错误日志: /var/log/nginx/${DOMAIN}_error.log"
    echo ""
    echo -e "${YELLOW}💡 提示: 如果无法访问，请检查：${NC}"
    echo "  1. DNS 解析是否正确"
    echo "  2. 防火墙是否开放 443 端口"
    echo "  3. 后端服务是否已启动"
    echo ""
else
    echo -e "${RED}❌ 配置测试失败${NC}"
    echo ""
    echo "请检查配置错误："
    sudo nginx -t
    exit 1
fi

