#!/bin/bash
# ============================================================
# nginx-ssl-setup.sh  Nginx + SSL 反向代理配置脚本
# 适用于：阿里云轻量应用服务器（zhenyuskill.com）
# 使用方式：
#   1. 从阿里云 SSL 证书服务下载 Nginx 格式证书
#   2. 将 .pem 和 .key 文件上传到服务器
#   3. 以 root 身份执行：bash nginx-ssl-setup.sh
# ============================================================
set -e

DOMAIN="zhenyuskill.com"
BACKEND_PORT=4000
SERVER_IP="47.76.173.254"
SSL_DIR="/etc/nginx/ssl/${DOMAIN}"
CERT_FILE="${SSL_DIR}/${DOMAIN}.pem"
KEY_FILE="${SSL_DIR}/${DOMAIN}.key"
NGINX_CONF="/etc/nginx/conf.d/zhenyuskill.conf"

echo "=== [1/9] 检查 root 权限 ==="
if [ "$(id -u)" -ne 0 ]; then
  echo "    ❌ 必须以 root 用户执行此脚本"
  echo "    请使用：sudo bash nginx-ssl-setup.sh"
  exit 1
fi
echo "    ✓ root 权限确认"

echo "=== [2/9] 安装 Nginx ==="
if command -v nginx &>/dev/null; then
  echo "    Nginx 已安装 ($(nginx -v 2>&1 | cut -d'/' -f2)) ✓"
else
  if [ -f /etc/debian_version ] || grep -qi ubuntu /etc/os-release 2>/dev/null; then
    apt-get update -q
    apt-get install -y -q nginx
  elif [ -f /etc/redhat-release ] || grep -qi 'centos\|rhel\|aliyun' /etc/os-release 2>/dev/null; then
    yum install -y nginx
  else
    echo "    ❌ 无法识别发行版，请手动安装 Nginx"
    exit 1
  fi
  echo "    ✓ Nginx 安装完成"
fi

echo "=== [3/9] 创建 SSL 证书目录 ==="
mkdir -p "${SSL_DIR}"
echo "    ✓ ${SSL_DIR}"

echo "=== [4/9] 检测 SSL 证书文件 ==="
if [ ! -f "${CERT_FILE}" ] || [ ! -f "${KEY_FILE}" ]; then
  echo ""
  echo "    ❌ SSL 证书文件不存在，请先上传证书："
  echo ""
  echo "    需要的文件："
  echo "      ${CERT_FILE}"
  echo "      ${KEY_FILE}"
  echo ""
  echo "    操作步骤："
  echo "      1. 登录阿里云 SSL 证书服务，下载 Nginx 格式证书"
  echo "      2. 将证书文件上传到服务器："
  echo "         scp ${DOMAIN}.pem root@${SERVER_IP}:${CERT_FILE}"
  echo "         scp ${DOMAIN}.key root@${SERVER_IP}:${KEY_FILE}"
  echo "      3. 重新执行本脚本"
  echo ""
  exit 1
fi
echo "    ✓ 证书文件已就位"

echo "=== [5/9] 生成 Nginx 配置文件 ==="
cat > "${NGINX_CONF}" << 'NGINX_EOF'
# HTTP -> HTTPS 重定向
server {
    listen 80;
    server_name zhenyuskill.com www.zhenyuskill.com;
    return 301 https://$host$request_uri;
}

# HTTPS 主配置
server {
    listen 443 ssl;
    server_name zhenyuskill.com www.zhenyuskill.com;

    ssl_certificate /etc/nginx/ssl/zhenyuskill.com/zhenyuskill.com.pem;
    ssl_certificate_key /etc/nginx/ssl/zhenyuskill.com/zhenyuskill.com.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    client_max_body_size 50m;

    location / {
        proxy_pass http://127.0.0.1:4000;
        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_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_http_version 1.1;
    }
}
NGINX_EOF
echo "    ✓ ${NGINX_CONF} 已生成"

echo "=== [6/9] 移除默认站点配置 ==="
if [ -f /etc/nginx/sites-enabled/default ]; then
  rm -f /etc/nginx/sites-enabled/default
  echo "    ✓ 已删除 /etc/nginx/sites-enabled/default"
else
  echo "    - 无默认站点配置，跳过"
fi

echo "=== [7/9] 配置防火墙（firewalld） ==="
if systemctl is-active --quiet firewalld 2>/dev/null; then
  firewall-cmd --permanent --add-service=http
  firewall-cmd --permanent --add-service=https
  firewall-cmd --reload
  echo "    ✓ firewalld 已开放 80/443 端口"
else
  echo "    - firewalld 未运行，跳过（请确认系统防火墙已放行 80/443）"
fi

echo "=== [8/9] 测试 Nginx 配置 ==="
nginx -t
echo "    ✓ 配置语法正确"

echo "=== [9/9] 启动 Nginx ==="
systemctl restart nginx
systemctl enable nginx
echo "    ✓ Nginx 已启动并设为开机自启"

echo ""
echo "========================================"
echo "✅ Nginx + SSL 配置完成！"
echo ""
echo "   域名：https://${DOMAIN}"
echo "   后端：http://127.0.0.1:${BACKEND_PORT} (PM2 管理)"
echo ""
echo "⚠️  还需要手动完成："
echo "   1. 阿里云控制台 → 轻量应用服务器 → 防火墙"
echo "      添加规则放行 TCP 80 和 TCP 443 端口"
echo "   2. 域名 DNS 设置 A 记录："
echo "      ${DOMAIN}     → ${SERVER_IP}"
echo "      www.${DOMAIN} → ${SERVER_IP}"
echo "========================================"
