#!/bin/bash

# RWADurian Admin Web SSL 证书配置脚本
# 使用 Let's Encrypt 申请 SSL 证书

set -e

DOMAIN="rwaadmin.szaiai.com"
EMAIL="admin@szaiai.com"  # 修改为你的邮箱
NGINX_CONF="/etc/nginx/sites-available/$DOMAIN"
NGINX_ENABLED="/etc/nginx/sites-enabled/$DOMAIN"
CERTBOT_WEBROOT="/var/www/certbot"

# 颜色定义
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 权限运行此脚本"
        exit 1
    fi
}

# 安装 Certbot
install_certbot() {
    log_info "检查 Certbot 安装..."

    if command -v certbot &> /dev/null; then
        log_success "Certbot 已安装"
        return
    fi

    log_info "安装 Certbot..."

    # Ubuntu/Debian
    if command -v apt &> /dev/null; then
        apt update
        apt install -y certbot python3-certbot-nginx
    # CentOS/RHEL
    elif command -v yum &> /dev/null; then
        yum install -y epel-release
        yum install -y certbot python3-certbot-nginx
    else
        log_error "不支持的系统，请手动安装 certbot"
        exit 1
    fi

    log_success "Certbot 安装完成"
}

# 配置 Nginx (首次，无 SSL)
setup_nginx_initial() {
    log_info "配置 Nginx (HTTP only，用于证书申请)..."

    # 创建临时配置文件（仅 HTTP）
    cat > "$NGINX_CONF" << 'EOF'
server {
    listen 80;
    listen [::]:80;
    server_name rwaadmin.szaiai.com;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        proxy_pass http://127.0.0.1:3000;
        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

    # 创建 certbot webroot 目录
    mkdir -p "$CERTBOT_WEBROOT"

    # 启用站点
    ln -sf "$NGINX_CONF" "$NGINX_ENABLED"

    # 测试并重载 Nginx
    nginx -t && systemctl reload nginx

    log_success "Nginx HTTP 配置完成"
}

# 申请 SSL 证书
obtain_certificate() {
    log_info "申请 Let's Encrypt SSL 证书..."

    certbot certonly \
        --webroot \
        --webroot-path="$CERTBOT_WEBROOT" \
        --email "$EMAIL" \
        --agree-tos \
        --no-eff-email \
        -d "$DOMAIN"

    log_success "SSL 证书申请成功"
}

# 配置 Nginx (完整 HTTPS)
setup_nginx_ssl() {
    log_info "配置 Nginx (HTTPS)..."

    # 获取脚本所在目录
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

    # 复制完整配置
    cp "$SCRIPT_DIR/rwaadmin.szaiai.com.conf" "$NGINX_CONF"

    # 测试并重载 Nginx
    nginx -t && systemctl reload nginx

    log_success "Nginx HTTPS 配置完成"
}

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

    # 测试续期
    certbot renew --dry-run

    log_success "自动续期配置完成 (cron job 已由 certbot 自动创建)"
}

# 显示帮助
show_help() {
    echo ""
    echo "RWADurian Admin Web SSL 配置脚本"
    echo ""
    echo "使用方法: sudo ./setup-ssl.sh [命令]"
    echo ""
    echo "命令:"
    echo "  install     完整安装 (默认)"
    echo "  renew       手动续期证书"
    echo "  status      查看证书状态"
    echo "  help        显示帮助"
    echo ""
    echo "注意: 运行前请确保:"
    echo "  1. 域名 DNS 已指向本服务器"
    echo "  2. 防火墙已开放 80 和 443 端口"
    echo "  3. Docker 应用已启动在 3000 端口"
    echo ""
}

# 完整安装
full_install() {
    check_root
    install_certbot
    setup_nginx_initial
    obtain_certificate
    setup_nginx_ssl
    setup_auto_renewal

    echo ""
    log_success "=========================================="
    log_success "SSL 配置完成!"
    log_success "访问地址: https://$DOMAIN"
    log_success "=========================================="
}

# 主函数
main() {
    case "${1:-install}" in
        install)
            full_install
            ;;
        renew)
            check_root
            certbot renew
            systemctl reload nginx
            ;;
        status)
            certbot certificates
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            log_error "未知命令: $1"
            show_help
            exit 1
            ;;
    esac
}

main "$@"
