name: 'Docker Build Action'
description: 'Build the docker image'
inputs:
  registry:
    required: true
    description: The registry to tag the image with
  image:
    required: true
    description: The image to tag the image with
  version:
    required: true
    description: The image version to tag with
  push:
    required: false
    description: Push the image?
    default: 'false'

outputs:
  tag:
    description: The docker tag of the built image
    value: ${{ steps.build_meta.outputs.tag }}
  version:
    description: The docker version of the built image
    value: ${{ steps.meta.outputs.version }}
  digest:
    description: The docker build digest of the built image
    value: ${{ steps.build_meta.outputs.digest }}

runs:
  using: 'composite'
  steps:
    - name: Context
      id: context
      shell: bash
      run: |
        git_repo_url="${{ github.server_url }}/${{ github.repository }}"

        echo "git_build_url=$git_repo_url/actions/runs/${{ github.run_id }}" >> $GITHUB_OUTPUT
        echo "git_sha=${{ github.sha }}" >> $GITHUB_OUTPUT
        echo "metadata_file=buildx-bake-metadata.json" >> $GITHUB_OUTPUT

        cat $GITHUB_OUTPUT

    - name: Docker meta
      id: meta
      uses: docker/metadata-action@902fa8ec7d6ecbf8d84d538b9b233a880e428804  # v5.7.0
      with:
        bake-target: web
        images: ${{ inputs.registry }}/${{ inputs.image }}
        tags: |
          # use raw tag to allow the calling workflow to define the version of the image
          # and to prevent multiple tags from being associated with a build
          type=raw,value=${{ inputs.version }}

    - name: Build Image
      id: build
      shell: bash
      env:
        # These values are irrelevant for local builds, so don't include them
        # in the make command directly but set them on the environment to be picked up.
        DOCKER_TAGS_FILE: ${{ steps.meta.outputs.bake-file-tags }}
        DOCKER_ANNOTATIONS_FILE: ${{ steps.meta.outputs.bake-file-annotations }}
        DOCKER_METADATA_FILE: ${{ steps.context.outputs.metadata_file }}
        DOCKER_PUSH: ${{ inputs.push }}
        version: ${{ steps.meta.outputs.version }}
        git_sha: ${{ steps.context.outputs.git_sha }}
        git_build_url: ${{ steps.context.outputs.git_build_url }}
      run: |
        make build \
          DOCKER_VERSION="$version" \
          DOCKER_COMMIT="$git_sha" \
          DOCKER_BUILD="$git_build_url"

    - name: Get image digest
      id: build_meta
      shell: bash
      env:
        metadata_file: ${{ steps.context.outputs.metadata_file }}
      run: |
        metadata=$(cat $metadata_file)
        echo "digest=$(echo $metadata | jq -r '.web."containerimage.digest"')" >> $GITHUB_OUTPUT
        echo "tag=$(echo $metadata | jq -r '.web."image.name"')" >> $GITHUB_OUTPUT
        cat $GITHUB_OUTPUT

