#!/usr/bin/env bash
set -euo pipefail

# Example CI script to build and push an image with buildx using registry cache.
# This script is provider-agnostic and intended to be run inside CI where
# Docker and buildx are available and authenticated against the registry.

REGISTRY=${REGISTRY:-ghcr.io/ORG/REPO}
IMAGE_TAG=${IMAGE_TAG:-staging}
CACHE_REF=${CACHE_REF:-${REGISTRY}:cache}

echo "Building ${REGISTRY}:${IMAGE_TAG} using registry cache ${CACHE_REF}"

docker buildx build \
  --push \
  --tag ${REGISTRY}:${IMAGE_TAG} \
  --cache-from type=registry,ref=${CACHE_REF} \
  --cache-to type=registry,ref=${CACHE_REF},mode=max \
  .

echo "Build complete. Image: ${REGISTRY}:${IMAGE_TAG}"

# Optional: instruct devs how to run locally with a local cache
cat <<'EOF'
Local test with BuildKit and local cache:
DOCKER_BUILDKIT=1 docker build \
  --tag myapp:staging \
  --cache-to=type=local,dest=/tmp/docker-cache \
  --cache-from=type=local,src=/tmp/docker-cache .

Prune local builder cache older than 72 hours:
docker builder prune --filter "until=72h" --force
EOF
