#!/bin/bash
# ============================================================
# 预览环境服务器初始化脚本
# 用途：在业务服务器上创建预览环境所需的目录和配置
# 使用方式：bash scripts/ci/preview_init_server.sh
# ============================================================

set -eu

PREVIEW_ROOT="/var/www/preview"
NGINX_CONF_PATH="/etc/nginx/conf.d/preview.conf"
DOMAIN="xiaoxiajianji.com"
STAGING_API="https://staging-api.xiaoxiajianji.com"

echo "=========================================="
echo "  预览环境服务器初始化"
echo "=========================================="
echo ""

# 1. 创建预览根目录
echo "[1/4] 创建预览根目录..."
if [ -d "$PREVIEW_ROOT" ]; then
  echo "  目录已存在: $PREVIEW_ROOT"
else
  mkdir -p "$PREVIEW_ROOT"
  echo "  已创建: $PREVIEW_ROOT"
fi
chown -R root:root "$PREVIEW_ROOT"
chmod -R 755 "$PREVIEW_ROOT"
echo ""

# 2. 创建测试页面（验证Nginx配置用）
echo "[2/4] 创建测试页面..."
TEST_DIR="${PREVIEW_ROOT}/pr-demo"
mkdir -p "$TEST_DIR"
cat > "$TEST_DIR/index.html" <<'EOF'
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>预览环境测试页</title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
               display: flex; align-items: center; justify-content: center;
               min-height: 100vh; margin: 0; background: #f5f5f5; }
        .card { background: white; padding: 40px; border-radius: 12px;
                box-shadow: 0 4px 6px rgba(0,0,0,0.1); text-align: center; max-width: 400px; }
        h1 { color: #2d3748; margin-top: 0; }
        .success { color: #38a169; font-size: 48px; margin: 20px 0; }
        p { color: #718096; line-height: 1.6; }
        code { background: #edf2f7; padding: 2px 6px; border-radius: 4px; font-size: 0.9em; }
    </style>
</head>
<body>
    <div class="card">
        <div class="success">✅</div>
        <h1>预览环境配置成功！</h1>
        <p>如果你能看到这个页面，说明 Nginx 预览环境配置正确。</p>
        <p>当前站点通过子域名 <code>pr-demo.preview</code> 路由到 <code>/var/www/preview/pr-demo/</code> 目录。</p>
    </div>
</body>
</html>
EOF
echo "  测试页面已创建: $TEST_DIR/index.html"
echo ""

# 3. 检查Nginx是否安装
echo "[3/4] 检查Nginx环境..."
if command -v nginx > /dev/null 2>&1; then
  echo "  Nginx 已安装: $(nginx -v 2>&1)"
  NGINX_INSTALLED=true
else
  echo "  ⚠️  Nginx 未安装，请先安装 Nginx"
  NGINX_INSTALLED=false
fi
echo ""

# 4. 输出Nginx配置建议
echo "[4/4] Nginx 配置建议"
echo ""
echo "----------------------------------------"
echo "  请将以下配置保存到: $NGINX_CONF_PATH"
echo "  或复制到 Nginx 配置目录中"
echo "----------------------------------------"
echo ""

cat <<'NGINX_CONF'
# ============================================================
# 预览环境 Nginx 配置
# 支持 *.preview.xiaoxiajianji.com 通配符子域名
# ============================================================

# 从子域名中提取 PR 号（如 pr-123.preview -> pr-123）
map $host $preview_pr {
    default "";
    ~^(?<pr>pr-\d+)\.preview\.xiaoxiajianji\.com$ $pr;
}

# HTTP 服务器（80端口）
server {
    listen 80;
    server_name *.preview.xiaoxiajianji.com;

    # 根目录根据子域名动态映射
    root /var/www/preview/$preview_pr;

    # 索引文件
    index index.html;

    # 字符集
    charset utf-8;

    # 访问日志
    access_log /var/log/nginx/preview_access.log;
    error_log /var/log/nginx/preview_error.log warn;

    # 如果子域名格式不正确，返回404
    if ($preview_pr = "") {
        return 404;
    }

    # 如果预览目录不存在，返回404
    if (!-d $document_root) {
        return 404;
    }

    # API 反向代理到 staging 环境
    location /api/ {
        proxy_pass https://staging-api.xiaoxiajianji.com/api/;
        proxy_http_version 1.1;
        proxy_set_header Host staging-api.xiaoxiajianji.com;
        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_set_header X-Forwarded-Host $host;

        # 超时设置
        proxy_connect_timeout 30s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;

        # 缓冲设置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;

        # WebSocket 支持（如需要）
        # proxy_set_header Upgrade $http_upgrade;
        # proxy_set_header Connection "upgrade";
    }

    # 静态资源缓存
    location /assets/ {
        expires 7d;
        add_header Cache-Control "public, max-age=604800, immutable";
        try_files $uri =404;
    }

    # SPA 路由支持
    location / {
        try_files $uri $uri/ /index.html;
    }

    # 安全相关响应头
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

    # 禁止隐藏文件访问
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }
}

# HTTPS 服务器（443端口）
# 注意：需要先配置 SSL 证书
# 建议使用 certbot 或手动配置证书
#
# server {
#     listen 443 ssl http2;
#     server_name *.preview.xiaoxiajianji.com;
#
#     # SSL 证书配置（请替换为实际证书路径）
#     ssl_certificate /path/to/fullchain.pem;
#     ssl_certificate_key /path/to/privkey.pem;
#
#     # 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;
#
#     # 其余配置与 HTTP 相同
#     root /var/www/preview/$preview_pr;
#     index index.html;
#     charset utf-8;
#
#     access_log /var/log/nginx/preview_ssl_access.log;
#     error_log /var/log/nginx/preview_ssl_error.log warn;
#
#     if ($preview_pr = "") {
#         return 404;
#     }
#
#     if (!-d $document_root) {
#         return 404;
#     }
#
#     location /api/ {
#         proxy_pass https://staging-api.xiaoxiajianji.com/api/;
#         proxy_http_version 1.1;
#         proxy_set_header Host staging-api.xiaoxiajianji.com;
#         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_set_header X-Forwarded-Host $host;
#         proxy_connect_timeout 30s;
#         proxy_send_timeout 60s;
#         proxy_read_timeout 60s;
#     }
#
#     location /assets/ {
#         expires 7d;
#         add_header Cache-Control "public, max-age=604800, immutable";
#         try_files $uri =404;
#     }
#
#     location / {
#         try_files $uri $uri/ /index.html;
#     }
#
#     add_header X-Frame-Options "SAMEORIGIN" always;
#     add_header X-Content-Type-Options "nosniff" always;
#     add_header X-XSS-Protection "1; mode=block" always;
#
#     location ~ /\. {
#         deny all;
#         access_log off;
#         log_not_found off;
#     }
# }
NGINX_CONF

echo ""
echo "----------------------------------------"
echo "  配置完成后的操作步骤："
echo "----------------------------------------"
echo ""
echo "1. 将上面的 Nginx 配置保存到合适的位置（如 /etc/nginx/conf.d/preview.conf）"
echo "2. 测试配置: nginx -t"
echo "3. 重载配置: nginx -s reload"
echo "4. 配置 DNS 解析: 将 *.preview.xiaoxiajianji.com 指向服务器 IP"
echo "5. 配置 SSL 证书（推荐使用 Let's Encrypt 通配符证书）"
echo ""
echo "测试方式："
echo "  访问 http://pr-demo.preview.xiaoxiajianji.com 验证配置"
echo ""
echo "=========================================="
echo "  初始化完成"
echo "=========================================="
