name: Create and publish a container image

on:
  push:
    # Publish main branch as `develop` image
    branches:
      - main

    # Publish tags as versioned release and `latest` image
    tags:
      - '*'

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  build-and-push-image:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v3
        # Need fetch-depth 0 to fetch tags, see https://github.com/actions/checkout/issues/701
        with:
          fetch-depth: 0

      - name: Gather context
        id: ctx
        run: |
          echo is_release=${{ contains(github.ref, 'refs/tags/') }} | tee -a $GITHUB_OUTPUT
          echo is_dev=${{ ! contains(github.ref, 'refs/tags/') }} | tee -a $GITHUB_OUTPUT
          echo version=$(git describe --always --tags) | tee -a $GITHUB_OUTPUT

      # QEMU is used to set up VMs for building non-x86_64 images.
      - name: Set up QEMU
        uses: docker/setup-qemu-action@v2
        with:
          platforms: "arm,arm64"

      # This is required to build multi-arch images.
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v2

      - name: Log in to registry
        uses: docker/login-action@v2
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Configure metadata
        id: meta
        uses: docker/metadata-action@v4
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
          # Configure to use `latest` and the PEP440 version from a tag name for
          # releases, and `develop` for non-release main builds.
          tags: |
            type=pep440,pattern={{ version }},enable=${{ steps.ctx.outputs.is_release }}
            type=raw,value=latest,enable=${{ steps.ctx.outputs.is_release }}
            type=raw,value=develop,enable=${{ steps.ctx.outputs.is_dev }}
          labels: |
            org.opencontainers.image.authors=opensource@aiven.io
            org.opencontainers.image.url=https://karapace.io
            org.opencontainers.image.documentation=https://github.com/aiven/karapace/
            org.opencontainers.image.vendor=Aiven
            org.opencontainers.image.licenses=Apache-2.0

      - uses: docker/build-push-action@v4
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          build-args: |
            KARAPACE_VERSION=${{ steps.ctx.outputs.version }}
          file: container/Dockerfile
          platforms: "linux/amd64,linux/arm64"