################################################################################
#  Licensed to the Apache Software Foundation (ASF) under one
#  or more contributor license agreements.  See the NOTICE file
#  distributed with this work for additional information
#  regarding copyright ownership.  The ASF licenses this file
#  to you under the Apache License, Version 2.0 (the
#  "License"); you may not use this file except in compliance
#  with the License.  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
# limitations under the License.
################################################################################

name: "Build Docker Image"
on:
  workflow_dispatch:
  push:
    branches:
      - main
      - 'release-*'
    tags:
      - 'release-*-rc*'
  pull_request:
    branches:
      - main
      - 'release-*'

jobs:
  build_image:
    runs-on: ubuntu-latest
    permissions:
      packages: write
      contents: read
    steps:
      - name: Check out the repo
        uses: actions/checkout@v4

      - name: Set up QEMU
        # Replaces docker/setup-qemu-action.
        # Keep this because docker-bake.hcl builds both amd64 and arm64.
        run: |
          docker run --privileged --rm tonistiigi/binfmt:qemu-v7.0.0 --install all

      - name: Set up Docker Build
        # Replaces docker/setup-buildx-action.
        # Create a named builder and bootstrap it so bake can use multi-platform builds.
        run: |
          docker buildx create --name builder --use || docker buildx use builder
          docker buildx inspect --bootstrap

      - name: Log in to the Container registry
        # Replaces docker/login-action.
        # PRs do not push images, so skip login there.
        if: github.event_name != 'pull_request'
        run: |
          echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u "${{ github.actor }}" --password-stdin

      - name: Extract metadata (tags, labels) for Docker
        id: meta
        # Replaces docker/metadata-action.
        #
        # The original workflow only consumed meta.outputs.bake-file.
        # We keep the same contract by generating a small temporary bake file
        # that augments the `docker-metadata-action` target defined in docker-bake.hcl.
        #
        # This preserves the existing `docker buildx bake -f ... -f ... bake-platform`
        # flow with a minimal diff.
        shell: bash
        run: |
          set -euo pipefail

          BAKE_FILE="$(mktemp)"
          IMAGE="ghcr.io/${GITHUB_REPOSITORY}"
          SHORT_SHA="${GITHUB_SHA::7}"

          TAGS=()
          TAGS+=("\"${IMAGE}:${SHORT_SHA}\"")

          # Match the original raw tag on the main branch.
          if [[ "${GITHUB_REF}" == "refs/heads/main" ]]; then
            TAGS+=("\"${IMAGE}:main\"")
          fi

          # Note: the original type=semver patterns are omitted here.
          # The workflow triggers on 'release-*-rc*' tags, which are not valid
          # semver (docker/metadata-action requires vX.Y.Z or X.Y.Z format), so
          # the original action produced no semver tags either.

          cat > "${BAKE_FILE}" <<EOF
          target "docker-metadata-action" {
            tags = [$(IFS=,; echo "${TAGS[*]}")]
            labels = {
              "org.opencontainers.image.source" = "https://github.com/${GITHUB_REPOSITORY}"
              "org.opencontainers.image.revision" = "${GITHUB_SHA}"
            }
          }
          EOF

          echo "bake-file=${BAKE_FILE}" >> "${GITHUB_OUTPUT}"

      - name: Build and push Docker images (supported platforms)
        # Replaces docker/bake-action while preserving the same inputs:
        # - the checked-in docker-bake.hcl
        # - the generated metadata bake file from the previous step
        run: |
          set -euo pipefail
          CMD=(docker buildx bake
            -f .github/workflows/docker-bake.hcl
            -f "${{ steps.meta.outputs.bake-file }}"
            bake-platform
          )
          if [[ "${{ github.event_name }}" != "pull_request" ]]; then
            CMD+=(--push)
          fi
          "${CMD[@]}"
