#!/bin/bash

# Data Import Export Service 部署脚本
# 使用方式: ./deploy.sh [dev|test|prod]

set -e

PROFILE=${1:-dev}
IMAGE_NAME="erp-data-import-export-service"
IMAGE_TAG="latest"
CONTAINER_NAME="erp-data-import-export-service"

echo "====== Data Import Export Service 部署脚本 ======"
echo "环境: $PROFILE"
echo "镜像: $IMAGE_NAME:$IMAGE_TAG"

# 构建镜像
build_image() {
    echo "[1/4] 构建Docker镜像..."
    docker build -t ${IMAGE_NAME}:${IMAGE_TAG} .
    echo "镜像构建完成"
}

# 停止并删除旧容器
deploy_container() {
    echo "[2/4] 部署容器..."
    
    # 停止旧容器
    if docker ps -a | grep -q ${CONTAINER_NAME}; then
        echo "停止旧容器..."
        docker stop ${CONTAINER_NAME} || true
        docker rm ${CONTAINER_NAME} || true
    fi
    
    # 启动新容器
    echo "启动新容器..."
    docker run -d \
        --name ${CONTAINER_NAME} \
        -p 8088:8088 \
        -e SPRING_PROFILES_ACTIVE=${PROFILE} \
        -v /tmp/import-export:/tmp/import-export \
        --restart unless-stopped \
        ${IMAGE_NAME}:${IMAGE_TAG}
    
    echo "容器启动完成"
}

# 检查健康状态
check_health() {
    echo "[3/4] 检查服务健康状态..."
    
    MAX_RETRIES=30
    RETRY_COUNT=0
    
    while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
        if curl -f http://localhost:8088/data-import/api/health > /dev/null 2>&1; then
            echo "服务健康检查通过"
            return 0
        fi
        
        RETRY_COUNT=$((RETRY_COUNT + 1))
        echo "等待服务启动... ($RETRY_COUNT/$MAX_RETRIES)"
        sleep 2
    done
    
    echo "服务健康检查失败"
    return 1
}

# 查看日志
show_logs() {
    echo "[4/4] 服务日志..."
    docker logs --tail=50 ${CONTAINER_NAME}
}

# 主流程
main() {
    case $PROFILE in
        dev|test|prod)
            build_image
            deploy_container
            check_health
            show_logs
            echo "====== 部署完成 ======"
            ;;
        *)
            echo "未知环境: $PROFILE"
            echo "支持的环境: dev, test, prod"
            exit 1
            ;;
    esac
}

main
