name: Build and push Docker image
description: Build and push Docker image to DockerHub and GitHub Container Registry

inputs:
  images:
    description: Name of the images to use as a base name
    required: true
  push_image:
    description: Whether to push the image to the registry (true/false)
    required: true
  directory:
    description: The directory containing the Dockerfile
    required: true
  tags:
    description: Comma separated tags to apply to the image
    required: true
  platforms:
    description: Platforms to build the image for (e.g. linux/amd64,linux/arm64)
    required: true

  dockerhub_repo:
    description: DockerHub repository name
    required: false
  dockerhub_description:
    description: Short description of the image
    required: false

runs:
  using: composite
  steps:
    - name: Login to DockerHub
      if: ${{ inputs.push_image == 'true' && inputs.dockerhub_repo != '' }}
      uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
      with:
        username: ${{ env.DOCKERHUB_USER }}
        password: ${{ env.DOCKERHUB_PW }}

    - name: Login to GitHub Container Registry
      if: ${{ inputs.push_image == 'true' }}
      uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
      with:
        registry: ghcr.io
        username: ${{ github.repository_owner }}
        password: ${{ env.GITHUB_TOKEN }}

    - uses: docker/setup-qemu-action@29109295f81e9208d7d86ff1c6c12d2833863392 # v3.6.0
      with:
        cache-image: false
    - uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0

    - uses: docker/metadata-action@902fa8ec7d6ecbf8d84d538b9b233a880e428804 # v5.7.0
      id: meta
      with:
        images: ${{ inputs.images }}
        tags: ${{ inputs.tags }}

    - name: Build and push
      uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
      with:
        context: ${{ inputs.directory }}
        platforms: ${{ inputs.platforms }}
        push: ${{ inputs.push_image == 'true' }}
        tags: ${{ steps.meta.outputs.tags }}

    - name: Update DockerHub description
      if: ${{ inputs.push_image == 'true' && inputs.dockerhub_repo != '' }}
      uses: peter-evans/dockerhub-description@432a30c9e07499fd01da9f8a49f0faf9e0ca5b77 # v4.0.2
      with:
        username: ${{ env.DOCKERHUB_USER }}
        password: ${{ env.DOCKERHUB_PW }}
        repository: ${{ inputs.dockerhub_repo }}
        short-description: ${{ inputs.dockerhub_description }}
        readme-filepath: ${{ inputs.directory }}/README.md
