#!/bin/bash
# ================================================
# Urban Lifeline - 后端服务镜像构建脚本
# 
# 使用方式:
#   ./build.sh           # 构建 All-in-One 镜像 (推荐)
#   ./build.sh base      # 仅构建基础镜像
# ================================================

set -e

# 项目根目录 (相对于此脚本)
PROJECT_ROOT="$(cd "$(dirname "$0")/../../.." && pwd)"
cd "$PROJECT_ROOT"

# 镜像版本
VERSION=${IMAGE_VERSION:-latest}

# 服务列表
SERVICES=(gateway system auth file log message crontab bidding workcase platform ai)

# 构建基础镜像
build_base() {
    echo "=========================================="
    echo "构建基础镜像: urban-lifeline-base-serv:${VERSION}"
    echo "=========================================="
    docker build -t urban-lifeline-base-serv:${VERSION} \
        -f docker/urbanLifeline/serv/Dockerfile.base .
    
    if [ "$VERSION" != "latest" ]; then
        docker tag urban-lifeline-base-serv:${VERSION} urban-lifeline-base-serv:latest
    fi
}

# 构建 All-in-One 镜像
build() {
    echo "=========================================="
    echo "构建 All-in-One 镜像: urban-lifeline-serv:${VERSION}"
    echo "=========================================="
    
    # 先构建基础镜像
    build_base
    
    # 检查所有 JAR 文件
    local missing=0
    for service in "${SERVICES[@]}"; do
        if ! ls urbanLifelineServ/${service}/target/*.jar 1> /dev/null 2>&1; then
            echo "缺少: urbanLifelineServ/${service}/target/*.jar"
            missing=1
        fi
    done
    
    if [ $missing -eq 1 ]; then
        echo ""
        echo "请先执行 Maven 构建:"
        echo "  cd urbanLifelineServ && mvn clean package -DskipTests"
        exit 1
    fi
    
    docker build -t urban-lifeline-serv:${VERSION} \
        -f docker/urbanLifeline/serv/Dockerfile.serv .
    
    if [ "$VERSION" != "latest" ]; then
        docker tag urban-lifeline-serv:${VERSION} urban-lifeline-serv:latest
    fi
    
    echo "=========================================="
    echo "镜像构建完成!"
    echo ""
    echo "管理服务:"
    echo "  docker exec urban-lifeline-serv /app/service-manager.sh status"
    echo "  docker exec urban-lifeline-serv /app/service-manager.sh restart gateway"
    echo "=========================================="
}

# 主逻辑
case "${1:-build}" in
    base)
        build_base
        ;;
    *)
        build
        ;;
esac
