name: Push Docker image

on:
  release:
    types: [published]
  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:
    inputs:
      tag:
        description: "Tag for the resulting images"
        type: string
        required: True
        default: 'stable'

env:
  TAG: ${{ inputs.tag || 'stable' }}
  DOCKER_HUB_OWNER: ${{ vars.DOCKER_HUB_OWNER || github.repository_owner }}

jobs:
  push_to_registry:
    name: Push Docker images to Docker Hub
    runs-on: ubuntu-latest
    strategy:
      matrix:
        image:
          # We build two images, `grist-oss` and `grist`.
          # See https://github.com/gristlabs/grist-core?tab=readme-ov-file#available-docker-images
          - name: "grist-oss"
            repo: "grist-core"
          - name: "grist"
            repo: "grist-ee"
    steps:
      - name: Check out the repo
        uses: actions/checkout@v3

      - name: Add a dummy ext/ directory
        run:
          mkdir ext && touch ext/dummy

      - name: Check out the ext/ directory
        if: matrix.image.name != 'grist-oss'
        run: buildtools/checkout-ext-directory.sh ${{ matrix.image.repo }}

      - name: Docker meta
        id: meta
        uses: docker/metadata-action@v4
        with:
          images: |
            ${{ github.repository_owner }}/${{ matrix.image.name }}
          tags: |
            type=ref,event=branch
            type=ref,event=pr
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=semver,pattern={{major}}
            ${{ env.TAG }}
      - name: Set up QEMU
        uses: docker/setup-qemu-action@v1

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

      - name: Log in to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}

      - name: Push to Docker Hub
        uses: docker/build-push-action@v2
        with:
          context: .
          push: true
          platforms: linux/amd64,linux/arm64/v8
          tags: ${{ steps.meta.outputs.tags }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          build-contexts: ext=ext

      - name: Push Enterprise to Docker Hub
        if: ${{ matrix.image.name == 'grist' }}
        uses: docker/build-push-action@v2
        with:
          context: .
          build-args: |
            BASE_IMAGE=${{ env.DOCKER_HUB_OWNER }}/${{ matrix.image.name}}
            BASE_VERSION=${{ env.TAG }}
          file: ext/Dockerfile
          platforms: ${{ env.PLATFORMS }}
          push: true
          tags: ${{ env.DOCKER_HUB_OWNER }}/grist-ee:${{ env.TAG }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
