#!/bin/bash
# PR构建专用：只构建不输出，验证Dockerfile能否正常构建
# 优先用buildx + 远程缓存，失败自动回退到普通docker build（DooD模式下buildx builder偶发崩溃）
set -eu

NO_CACHE_FLAG=""
if [ "$1" = "--no-cache" ]; then
  NO_CACHE_FLAG="--no-cache"
  shift
fi

DOCKERFILE="$1"
IMAGE_TAG="$2"
CACHE_REF="$3"
shift 3
BUILD_ARGS=""
for arg in "$@"; do
  BUILD_ARGS="$BUILD_ARGS --build-arg $arg"
done

BUILDER_NAME="ci-pr-builder-${GITHUB_RUN_ID:-local}"

echo "=== PR Build: buildx + remote cache (attempt 1) ==="
echo "Dockerfile: ${DOCKERFILE}"
echo "Image tag: ${IMAGE_TAG}"
echo ""

# --- 尝试 buildx docker-container driver ---
if ! docker buildx inspect "$BUILDER_NAME" > /dev/null 2>&1; then
  docker buildx create --use --name "$BUILDER_NAME" --driver docker-container 2>/dev/null || true
else
  docker buildx use "$BUILDER_NAME" 2>/dev/null || true
fi
docker buildx inspect --bootstrap > /dev/null 2>&1 || true

set +e
docker buildx build \
  $NO_CACHE_FLAG \
  $BUILD_ARGS \
  --cache-from "type=registry,ref=${CACHE_REF}" \
  -f "${DOCKERFILE}" \
  -t "${IMAGE_TAG}" \
  --load \
  .
BUILDX_EXIT=$?
set -e

if [ $BUILDX_EXIT -eq 0 ]; then
  echo ""
  echo "PR build OK (buildx): ${IMAGE_TAG}"
  exit 0
fi

echo ""
echo "⚠️  buildx build失败，回退到普通docker build"
echo "   原因：buildx builder在DooD模式下偶发不稳定（graceful_stop / buildkitd.sock）"
echo ""

# 清理 buildx builder
docker buildx rm "$BUILDER_NAME" 2>/dev/null || true

# --- 回退：普通 docker build ---
# 注意：普通docker build不支持远程缓存，但更稳定
set +e
docker build \
  $NO_CACHE_FLAG \
  $BUILD_ARGS \
  -f "${DOCKERFILE}" \
  -t "${IMAGE_TAG}" \
  .
DOCKER_EXIT=$?
set -e

if [ $DOCKER_EXIT -eq 0 ]; then
  echo ""
  echo "PR build OK (fallback docker build): ${IMAGE_TAG}"
  exit 0
fi

echo ""
echo "❌ PR build failed (both buildx and docker build)"
exit 1
