#!/bin/bash
# RWADurian Mobile Upgrade - Nginx 完整安装脚本
# 适用于全新 Ubuntu/Debian 服务器

set -e

DOMAIN="update.szaiai.com"
EMAIL="admin@szaiai.com"  # 修改为你的邮箱
APP_PORT=3020

# 颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# 检查 root 权限
check_root() {
    if [ "$EUID" -ne 0 ]; then
        log_error "请使用 root 权限运行: sudo ./install.sh"
        exit 1
    fi
}

# 步骤 1: 更新系统
update_system() {
    log_info "步骤 1/6: 更新系统包..."
    apt update && apt upgrade -y
    log_success "系统更新完成"
}

# 步骤 2: 安装 Nginx
install_nginx() {
    log_info "步骤 2/6: 安装 Nginx..."
    apt install -y nginx
    systemctl enable nginx
    systemctl start nginx
    log_success "Nginx 安装完成"
}

# 步骤 3: 安装 Certbot
install_certbot() {
    log_info "步骤 3/6: 安装 Certbot..."
    apt install -y certbot python3-certbot-nginx
    log_success "Certbot 安装完成"
}

# 步骤 4: 配置 Nginx (HTTP)
configure_nginx_http() {
    log_info "步骤 4/6: 配置 Nginx (HTTP 临时配置用于证书申请)..."

    # 创建 certbot webroot 目录
    mkdir -p /var/www/certbot

    # 创建临时 HTTP 配置
    cat > /etc/nginx/sites-available/$DOMAIN << EOF
# 临时 HTTP 配置 - 用于 Let's Encrypt 验证
server {
    listen 80;
    listen [::]:80;
    server_name $DOMAIN;

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

    # 临时代理到应用
    location / {
        proxy_pass http://127.0.0.1:$APP_PORT;
        proxy_http_version 1.1;
        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;
    }
}
EOF

    # 启用站点
    ln -sf /etc/nginx/sites-available/$DOMAIN /etc/nginx/sites-enabled/

    # 删除默认站点 (可选)
    rm -f /etc/nginx/sites-enabled/default

    # 测试并重载
    nginx -t && systemctl reload nginx
    log_success "Nginx HTTP 配置完成"
}

# 步骤 5: 申请 SSL 证书
obtain_ssl_certificate() {
    log_info "步骤 5/6: 申请 Let's Encrypt SSL 证书..."

    # 检查域名解析
    log_info "检查域名 $DOMAIN 解析..."
    if ! host $DOMAIN > /dev/null 2>&1; then
        log_warn "无法解析域名 $DOMAIN，请确保 DNS 已正确配置"
        log_warn "继续尝试申请证书..."
    fi

    # 申请证书
    certbot certonly \
        --webroot \
        --webroot-path=/var/www/certbot \
        --email $EMAIL \
        --agree-tos \
        --no-eff-email \
        -d $DOMAIN

    log_success "SSL 证书申请成功"
}

# 步骤 6: 配置 Nginx (HTTPS)
configure_nginx_https() {
    log_info "步骤 6/6: 配置 Nginx (HTTPS)..."

    # 复制完整的 HTTPS 配置
    cat > /etc/nginx/sites-available/$DOMAIN << 'NGINX_CONF'
# RWADurian Mobile Upgrade Nginx 配置
# 域名: update.szaiai.com

# HTTP 重定向到 HTTPS
server {
    listen 80;
    listen [::]:80;
    server_name update.szaiai.com;

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

    # 重定向到 HTTPS
    location / {
        return 301 https://$host$request_uri;
    }
}

# HTTPS 配置
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name update.szaiai.com;

    # SSL 证书 (Let's Encrypt)
    ssl_certificate /etc/letsencrypt/live/update.szaiai.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/update.szaiai.com/privkey.pem;

    # SSL 配置优化
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;

    # 现代加密套件
    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:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;

    # HSTS
    add_header Strict-Transport-Security "max-age=63072000" always;

    # 日志
    access_log /var/log/nginx/update.szaiai.com.access.log;
    error_log /var/log/nginx/update.szaiai.com.error.log;

    # Gzip 压缩
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/xml application/json application/javascript application/rss+xml application/atom+xml image/svg+xml;

    # 安全头
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    # 反向代理到 Docker 容器
    location / {
        proxy_pass http://127.0.0.1:3020;
        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;
    }

    # 健康检查端点
    location /api/health {
        proxy_pass http://127.0.0.1:3020;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        access_log off;
    }

    # 静态资源缓存
    location /_next/static {
        proxy_pass http://127.0.0.1:3020;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        add_header Cache-Control "public, max-age=31536000, immutable";
    }
}
NGINX_CONF

    # 测试并重载
    nginx -t && systemctl reload nginx
    log_success "Nginx HTTPS 配置完成"
}

# 配置证书自动续期
setup_auto_renewal() {
    log_info "配置证书自动续期..."

    # Certbot 会自动创建 systemd timer 或 cron job
    # 测试续期
    certbot renew --dry-run

    log_success "证书自动续期已配置"
}

# 配置防火墙
configure_firewall() {
    log_info "配置防火墙..."

    if command -v ufw &> /dev/null; then
        ufw allow 'Nginx Full'
        ufw allow OpenSSH
        ufw --force enable
        log_success "UFW 防火墙已配置"
    else
        log_warn "未检测到 UFW，请手动配置防火墙开放 80 和 443 端口"
    fi
}

# 显示完成信息
show_completion() {
    echo ""
    echo -e "${GREEN}========================================${NC}"
    echo -e "${GREEN}   安装完成!${NC}"
    echo -e "${GREEN}========================================${NC}"
    echo ""
    echo -e "访问地址: ${BLUE}https://$DOMAIN${NC}"
    echo ""
    echo "常用命令:"
    echo "  查看 Nginx 状态:  systemctl status nginx"
    echo "  重载 Nginx:       systemctl reload nginx"
    echo "  查看证书:         certbot certificates"
    echo "  手动续期:         certbot renew"
    echo "  查看日志:         tail -f /var/log/nginx/$DOMAIN.access.log"
    echo ""
}

# 主函数
main() {
    echo ""
    echo "============================================"
    echo "  RWADurian Mobile Upgrade - Nginx 安装脚本"
    echo "  域名: $DOMAIN"
    echo "============================================"
    echo ""

    check_root
    update_system
    install_nginx
    install_certbot
    configure_firewall
    configure_nginx_http

    echo ""
    log_warn "请确保以下条件已满足:"
    echo "  1. 域名 $DOMAIN 的 DNS A 记录已指向本服务器 IP"
    echo "  2. Docker 应用已在端口 $APP_PORT 运行"
    echo ""
    read -p "是否继续申请 SSL 证书? (y/n): " confirm

    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        obtain_ssl_certificate
        configure_nginx_https
        setup_auto_renewal
        show_completion
    else
        log_info "已跳过 SSL 配置，当前为 HTTP 模式"
        log_info "稍后可运行: certbot --nginx -d $DOMAIN"
    fi
}

main "$@"
