#!/bin/bash
# PR构建专用：只构建不输出，验证Dockerfile能否正常构建
# 无本地缓存（12个runner不共享，反而添乱），只用ACR远程缓存
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}"
if ! docker buildx inspect "$BUILDER_NAME" > /dev/null 2>&1; then
  docker buildx create --use --name "$BUILDER_NAME" --driver docker-container
else
  docker buildx use "$BUILDER_NAME"
fi
docker buildx inspect --bootstrap

echo "=== PR Build: build only, no output, remote cache only ==="
echo "Dockerfile: ${DOCKERFILE}"
echo "Image tag: ${IMAGE_TAG}"
echo ""

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

echo ""
echo "PR build OK (build only, no output): ${IMAGE_TAG}"
