#!/bin/bash

# SSL证书配置脚本
set -e

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

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查域名
check_domain() {
    local domain=$1
    if [ -z "$domain" ]; then
        log_error "请提供域名"
        exit 1
    fi
    
    log_info "检查域名: $domain"
    if ! nslookup $domain > /dev/null 2>&1; then
        log_warning "域名解析失败，请确保域名已正确配置"
    fi
}

# 使用Let's Encrypt获取证书
setup_letsencrypt() {
    local domain=$1
    local email=$2
    
    log_info "使用Let's Encrypt获取SSL证书..."
    
    # 安装certbot
    if ! command -v certbot &> /dev/null; then
        log_info "安装certbot..."
        if command -v apt-get &> /dev/null; then
            sudo apt-get update
            sudo apt-get install -y certbot
        elif command -v yum &> /dev/null; then
            sudo yum install -y certbot
        else
            log_error "无法自动安装certbot，请手动安装"
            exit 1
        fi
    fi
    
    # 创建webroot目录
    mkdir -p /var/www/certbot
    
    # 获取证书
    sudo certbot certonly \
        --webroot \
        --webroot-path=/var/www/certbot \
        --email $email \
        --agree-tos \
        --no-eff-email \
        -d $domain
    
    # 复制证书到项目目录
    sudo cp /etc/letsencrypt/live/$domain/fullchain.pem ssl/
    sudo cp /etc/letsencrypt/live/$domain/privkey.pem ssl/
    sudo chown $(whoami):$(whoami) ssl/*.pem
    
    log_info "SSL证书配置完成"
}

# 生成自签名证书（开发/测试用）
setup_selfsigned() {
    local domain=$1
    
    log_info "生成自签名SSL证书..."
    
    # 创建ssl目录
    mkdir -p ssl
    
    # 生成私钥
    openssl genrsa -out ssl/privkey.pem 2048
    
    # 生成证书
    openssl req -new -x509 -key ssl/privkey.pem -out ssl/fullchain.pem -days 365 \
        -subj "/C=CN/ST=State/L=City/O=Organization/CN=$domain"
    
    log_warning "已生成自签名证书，仅用于开发/测试环境"
    log_warning "生产环境请使用有效的SSL证书"
}

# 配置证书自动续期
setup_auto_renewal() {
    local domain=$1
    
    log_info "配置证书自动续期..."
    
    # 创建续期脚本
    cat > ssl-renew.sh << EOF
#!/bin/bash
certbot renew --quiet
if [ \$? -eq 0 ]; then
    cp /etc/letsencrypt/live/$domain/fullchain.pem ssl/
    cp /etc/letsencrypt/live/$domain/privkey.pem ssl/
    docker-compose -f docker-compose.prod.yml restart nginx-proxy
fi
EOF
    
    chmod +x ssl-renew.sh
    
    # 添加到crontab
    (crontab -l 2>/dev/null; echo "0 3 * * * $(pwd)/ssl-renew.sh") | crontab -
    
    log_info "证书自动续期配置完成"
}

# 主函数
main() {
    echo "🔒 SSL证书配置脚本"
    echo "=================="
    
    read -p "请输入域名: " DOMAIN
    check_domain $DOMAIN
    
    echo ""
    echo "请选择证书类型："
    echo "1) Let's Encrypt (免费，推荐生产环境)"
    echo "2) 自签名证书 (开发/测试环境)"
    echo ""
    read -p "请输入选择 (1-2): " choice
    
    case $choice in
        1)
            read -p "请输入邮箱地址: " EMAIL
            if [ -z "$EMAIL" ]; then
                log_error "邮箱地址不能为空"
                exit 1
            fi
            setup_letsencrypt $DOMAIN $EMAIL
            setup_auto_renewal $DOMAIN
            ;;
        2)
            setup_selfsigned $DOMAIN
            ;;
        *)
            log_error "无效选择"
            exit 1
            ;;
    esac
    
    # 更新nginx配置中的域名
    if [ -f "nginx-proxy.conf" ]; then
        sed -i "s/your-domain.com/$DOMAIN/g" nginx-proxy.conf
        log_info "已更新nginx配置中的域名"
    fi
    
    # 更新环境配置
    if [ -f ".env.production" ]; then
        sed -i "s/DOMAIN=your-domain.com/DOMAIN=$DOMAIN/g" .env.production
        log_info "已更新环境配置中的域名"
    fi
    
    echo ""
    log_info "SSL证书配置完成！"
    echo "证书文件位置:"
    echo "  - 证书: ssl/fullchain.pem"
    echo "  - 私钥: ssl/privkey.pem"
    echo ""
    echo "现在可以使用HTTPS模式部署:"
    echo "  ./deploy-prod.sh https"
}

# 运行主函数
main "$@"
