#!/bin/bash
# 构建带有预装 APT 包的基础镜像
# Usage: ./build-base-images.sh [output-dir]

set -e

OUTPUT_DIR="${1:-./build-cache}"
IMAGES_DIR="$OUTPUT_DIR/images"

mkdir -p "$IMAGES_DIR"

echo "======================================"
echo "构建预装 APT 包的基础镜像"
echo "======================================"

# 构建各个基础镜像
echo ""
echo "1. 构建 datamate-java-base (用于 backend, gateway)..."
docker build \
    -t datamate-java-base:latest \
    --target datamate-java-base \
    -f scripts/offline/Dockerfile.base-images \
    . || echo "Warning: datamate-java-base 构建失败"

echo ""
echo "2. 构建 datamate-python-base (用于 backend-python)..."
docker build \
    -t datamate-python-base:latest \
    --target datamate-python-base \
    -f scripts/offline/Dockerfile.base-images \
    . || echo "Warning: datamate-python-base 构建失败"

echo ""
echo "3. 构建 datamate-runtime-base (用于 runtime)..."
docker build \
    -t datamate-runtime-base:latest \
    --target datamate-runtime-base \
    -f scripts/offline/Dockerfile.base-images \
    . || echo "Warning: datamate-runtime-base 构建失败"

echo ""
echo "4. 构建 deer-flow-backend-base (用于 deer-flow-backend)..."
docker build \
    -t deer-flow-backend-base:latest \
    --target deer-flow-backend-base \
    -f scripts/offline/Dockerfile.base-images \
    . || echo "Warning: deer-flow-backend-base 构建失败"

echo ""
echo "5. 构建 mineru-base (用于 mineru)..."
docker build \
    -t mineru-base:latest \
    --target mineru-base \
    -f scripts/offline/Dockerfile.base-images \
    . || echo "Warning: mineru-base 构建失败"

echo ""
echo "======================================"
echo "保存基础镜像集合"
echo "======================================"

docker save -o "$IMAGES_DIR/base-images-with-apt.tar" \
    maven:3-eclipse-temurin-21 \
    maven:3-eclipse-temurin-8 \
    eclipse-temurin:21-jdk \
    mysql:8 \
    node:20-alpine \
    nginx:1.29 \
    ghcr.nju.edu.cn/astral-sh/uv:python3.11-bookworm \
    ghcr.nju.edu.cn/astral-sh/uv:python3.12-bookworm \
    ghcr.nju.edu.cn/astral-sh/uv:latest \
    python:3.12-slim \
    python:3.11-slim \
    gcr.io/distroless/nodejs20-debian12 \
    datamate-java-base:latest \
    datamate-python-base:latest \
    datamate-runtime-base:latest \
    deer-flow-backend-base:latest \
    mineru-base:latest \
    2>/dev/null || echo "Warning: 部分镜像保存失败"

echo ""
echo "======================================"
echo "✓ 基础镜像构建完成"
echo "======================================"
echo "镜像列表:"
docker images | grep -E "(datamate-|deer-flow-|mineru-)base" || true
