name: Publish container image

on:
  push:
    tags:
      # Matches stable and pre-releases
      - "[0-9]+.[0-9]+.[0-9]+*"

jobs:
  docker:
    runs-on: ubuntu-20.04
    permissions:
      contents: read
      packages: write

    steps:
      - name: Checkout
        uses: actions/checkout@v3

      # Outputs the name of the repository (owner/repo)
      - name: Get image name
        id: image
        run: |
          IMAGE_NAME=$(echo ${{ github.repository }} | tr '[:upper:]' '[:lower:]')
          echo "image_name=ghcr.io/${IMAGE_NAME}" >> $GITHUB_OUTPUT

      # Tags stable versions as :latest
      # Pre-releases, alphas, etc. as :snapshot
      - name: Output image tags from git tag events
        if: ${{ startsWith(github.ref, 'refs/tags/') }}
        run: |
          # Remove everything else than the tagged version
          DASHBOARD_VERSION=${GITHUB_REF#refs/tags/}
          echo "
          DASHBOARD_VERSION=${DASHBOARD_VERSION}
          CONTAINER_TAGS=${{ steps.image.outputs.image_name }}:${DASHBOARD_VERSION}
          " >> "${GITHUB_ENV}"

      - name: Set up Docker QEMU
        uses: docker/setup-qemu-action@v1
        with:
          platforms: arm64

      - name: Set up Docker Buildx
        id: buildx
        uses: docker/setup-buildx-action@v1

      - name: Login to GitHub Container Registry
        uses: docker/login-action@v1
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and Push
        id: docker_build
        uses: docker/build-push-action@v2
        with:
          builder: ${{ steps.buildx.outputs.name }}
          context: ./
          platforms: linux/amd64,linux/arm64
          push: true
          tags: ${{ env.CONTAINER_TAGS }}
          cache-from: type=local,src=/tmp/.buildx-cache
          cache-to: type=local,dest=/tmp/.buildx-cache
          build-args: |
            COMMIT_ID=${{ github.sha }}
            PROJECT_VERSION=$DASHBOARD_VERSION

      - name: Output image digest
        run: |
          echo $"\
            Digest: ${{ steps.docker_build.outputs.digest }}
            Tags: ${{ env.CONTAINER_TAGS }}"
