#!/bin/bash
# 部署脚本

set -e

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

# 函数定义
log() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

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

info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

# 获取参数
ENVIRONMENT=${1:-production}
ACTION=${2:-up}

log "考培练系统前端部署脚本"
log "环境: $ENVIRONMENT"
log "操作: $ACTION"

# 检查 docker-compose 是否安装
if ! command -v docker-compose &> /dev/null; then
    if command -v docker &> /dev/null && docker compose version &> /dev/null; then
        DOCKER_COMPOSE="docker compose"
    else
        error "docker-compose 或 docker compose 未找到"
        exit 1
    fi
else
    DOCKER_COMPOSE="docker-compose"
fi

# 设置配置文件
if [ "$ENVIRONMENT" = "development" ]; then
    COMPOSE_FILE="docker-compose.dev.yml"
else
    COMPOSE_FILE="docker-compose.yml"
fi

# 检查配置文件是否存在
if [ ! -f "$COMPOSE_FILE" ]; then
    error "配置文件 $COMPOSE_FILE 不存在"
    exit 1
fi

# 执行操作
case $ACTION in
    up)
        log "启动服务..."
        $DOCKER_COMPOSE -f "$COMPOSE_FILE" up -d
        ;;
    down)
        log "停止服务..."
        $DOCKER_COMPOSE -f "$COMPOSE_FILE" down
        ;;
    restart)
        log "重启服务..."
        $DOCKER_COMPOSE -f "$COMPOSE_FILE" down
        $DOCKER_COMPOSE -f "$COMPOSE_FILE" up -d
        ;;
    logs)
        log "查看日志..."
        $DOCKER_COMPOSE -f "$COMPOSE_FILE" logs -f
        ;;
    ps)
        log "查看服务状态..."
        $DOCKER_COMPOSE -f "$COMPOSE_FILE" ps
        ;;
    build)
        log "构建并启动服务..."
        $DOCKER_COMPOSE -f "$COMPOSE_FILE" up -d --build
        ;;
    clean)
        log "清理服务和数据..."
        warn "这将删除所有容器和数据卷，确定继续吗？(y/N)"
        read -r response
        if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
            $DOCKER_COMPOSE -f "$COMPOSE_FILE" down -v --rmi all
            docker system prune -f
        else
            log "操作已取消"
        fi
        ;;
    *)
        error "未知操作: $ACTION"
        echo "可用操作: up, down, restart, logs, ps, build, clean"
        exit 1
        ;;
esac

# 显示服务状态
if [ "$ACTION" = "up" ] || [ "$ACTION" = "restart" ] || [ "$ACTION" = "build" ]; then
    log "等待服务启动..."
    sleep 5
    
    log "服务状态:"
    $DOCKER_COMPOSE -f "$COMPOSE_FILE" ps
    
    if [ "$ENVIRONMENT" = "development" ]; then
        info "开发环境访问地址:"
        info "前端: http://localhost:3001"
        info "后端: http://localhost:8000"
        info "数据库: localhost:3307"
        info "Redis: localhost:6380"
        info "邮件服务: http://localhost:8025"
    else
        info "生产环境访问地址:"
        info "前端: http://localhost:3001"
        info "后端: http://localhost:8000"
        info "数据库: localhost:3306"
        info "Redis: localhost:6379"
    fi
fi

log "部署完成！"
