name: Release to Docker Hub

on:
    workflow_call:
      inputs:
        service-name:
          required: true
          type: string
        working-directory:
          required: true
          type: string
  
jobs:
    docker:
      name: Build and Push Backend image to Docker Hub
      runs-on: ubuntu-latest
      steps:
        - uses: actions/github-script@v6
          id: create_image_tag
          with:
            script: |
              if(github.ref == 'refs/heads/main') {
                return 'latest';
              } else if(context.issue.number) {
                return "pr" + context.issue.number;
              } else {
                return "pr" + (
                  await github.rest.repos.listPullRequestsAssociatedWithCommit({
                    commit_sha: context.sha,
                    owner: context.repo.owner,
                    repo: context.repo.repo,
                  })
                ).data[0].number;
              }
            result-encoding: string
        - name: Image tag
          run: echo '${{steps.create_image_tag.outputs.result}}'

        - name: Set up QEMU
          uses: docker/setup-qemu-action@v3
        - name: Set up Docker Buildx
          uses: docker/setup-buildx-action@v3
        - name: Login to Docker Hub
          uses: docker/login-action@v3
          with:
            username: ${{ secrets.DOCKERHUB_USERNAME }}
            password: ${{ secrets.DOCKERHUB_TOKEN }}
        - name: Build and push
          uses: docker/build-push-action@v5
          with:
            push: true
            context: "{{defaultContext}}:${{ inputs.working-directory }}"
            tags: vcscsvcscs/${{ inputs.service-name }}:${{steps.create_image_tag.outputs.result}}
            platforms: linux/amd64, linux/arm64