#!/bin/bash

# 考陪练系统部署脚本
# 用于部署前端、后端服务并申请SSL证书

set -e

echo "=== 考陪练系统部署开始 ==="

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    echo "❌ Docker未运行，请先启动Docker服务"
    exit 1
fi

# 检查Docker Compose是否安装
if ! command -v docker-compose > /dev/null 2>&1; then
    echo "❌ Docker Compose未安装"
    exit 1
fi

echo "✅ Docker环境检查通过"

# 创建必要的目录
echo "📁 创建必要的目录..."
mkdir -p /root/aiedu/kaopeilian-backend/logs
mkdir -p /root/aiedu/kaopeilian-backend/uploads
mkdir -p /root/aiedu/nginx/conf.d

# 停止现有容器
echo "🛑 停止现有容器..."
docker-compose down || true

# 构建镜像
echo "🔨 构建Docker镜像..."
docker-compose build --no-cache

# 启动服务（除了nginx，因为还没有SSL证书）
echo "🚀 启动后端和前端服务..."
docker-compose up -d kaopeilian-redis kaopeilian-backend kaopeilian-frontend

# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 30

# 检查服务健康状态
echo "🔍 检查服务健康状态..."
if curl -f http://localhost:8000/health > /dev/null 2>&1; then
    echo "✅ 后端服务健康检查通过"
else
    echo "❌ 后端服务健康检查失败"
    docker-compose logs kaopeilian-backend
    exit 1
fi

if curl -f http://localhost:3001/ > /dev/null 2>&1; then
    echo "✅ 前端服务健康检查通过"
else
    echo "❌ 前端服务健康检查失败"
    docker-compose logs kaopeilian-frontend
    exit 1
fi

echo "=== 基础服务部署完成 ==="
echo "前端访问地址: http://localhost:3001"
echo "后端API地址: http://localhost:8000"
echo ""
echo "下一步将申请SSL证书..."

# 申请SSL证书
echo "🔐 申请SSL证书..."
if command -v certbot > /dev/null 2>&1; then
    # 停止nginx容器（如果运行）
    docker-compose stop kaopeilian-nginx || true
    
    # 使用standalone模式申请证书
    certbot certonly \
        --standalone \
        --non-interactive \
        --agree-tos \
        --email admin@ireborn.com.cn \
        --domains aiedu.ireborn.com.cn \
        --pre-hook "docker-compose stop kaopeilian-nginx" \
        --post-hook "docker-compose up -d kaopeilian-nginx"
    
    if [ $? -eq 0 ]; then
        echo "✅ SSL证书申请成功"
        
        # 启动nginx服务
        echo "🚀 启动Nginx反向代理服务..."
        docker-compose up -d kaopeilian-nginx
        
        echo "=== 部署完成 ==="
        echo "HTTPS访问地址: https://aiedu.ireborn.com.cn"
        echo "前端访问地址: https://aiedu.ireborn.com.cn"
        echo "后端API地址: https://aiedu.ireborn.com.cn/api"
    else
        echo "❌ SSL证书申请失败，请检查域名配置"
        echo "HTTP访问地址: http://aiedu.ireborn.com.cn"
    fi
else
    echo "⚠️  certbot未安装，跳过SSL证书申请"
    echo "请手动安装certbot并申请SSL证书"
fi

echo ""
echo "=== 部署完成 ==="
echo "查看服务状态: docker-compose ps"
echo "查看日志: docker-compose logs [服务名]"
echo "停止服务: docker-compose down"



