name: Publish to dockerhub

on:
  push:
    branches:
      - main
    paths-ignore:
      - website/**
  workflow_call:
    inputs:
      version:
        description: "Which version to release"
        type: 'string'
        required: true
      is-latest-version:
        description: Is this the latest version? If latest we'll update the version docker
        required: true
        type: boolean
        default: true
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        version: [ 20.14.0-alpine ]
    steps:
      - name: Checkout tag v${{ inputs.version }}
        if: ${{ inputs.version != '' }}
        uses: actions/checkout@v4
        with:
          ref: v${{ inputs.version }} # tag that should be created by the caller workflow
      - name: Checkout
        if: ${{ inputs.version == '' }}
        uses: actions/checkout@v4
      - name: Setup QEmu so we can build multiplatform
        uses: docker/setup-qemu-action@v3
      - name: Setup Docker buildx
        uses: docker/setup-buildx-action@v3
      - name: Docker meta configuration
        uses: docker/metadata-action@v5
        id: meta
        with:
          images: |
            unleashorg/unleash-server
          flavor: latest=${{ github.event.inputs.is-latest-version || 'auto' }}
          tags: |
            # only enabled for workflow dispatch except main (assume its a release):
            type=semver,pattern={{ version }},enable=${{ github.event_name == 'workflow_dispatch' && inputs.version != '' }},value=${{ inputs.version }}
            type=semver,pattern={{ major }}.{{ minor }},enable=${{ github.event_name == 'workflow_dispatch' && inputs.version != '' }},value=${{ inputs.version }}
            type=semver,pattern={{ major }},enable=${{ github.event_name == 'workflow_dispatch' && inputs.version != '' }},value=${{ inputs.version }}
            # only enabled in main:
            type=edge,prefix=main-,suffix=-${{ matrix.version }},enable=${{ github.ref == 'refs/heads/main' }}
            # only enabled on workflow_dispatch:
            type=sha,suffix=-${{ matrix.version }},enable=${{ github.event_name == 'workflow_dispatch' }}
      - name: Login to docker hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}
      - name: Build tag and push image to Docker hub
        uses: docker/build-push-action@v6
        with:
          context: .
          platforms: linux/amd64,linux/arm64
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          build-args: NODE_VERSION=${{ matrix.version }}
          cache-from: type=gha
          cache-to: type=gha,mode=max