on:
  workflow_call:
    inputs:
      registry:
        default: ghcr.io
        type: string
      imageName:
        default: ${{ github.repository_owner }}
        type: string
      cliVersion:
        required: true
        type: string

jobs:
  build-cli-docker-image:
    name: Build CLI Docker Image
    runs-on: ubuntu-22.04
    permissions:
      contents: read
      packages: write
      pull-requests: write
    steps:
      - name: checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 2
      - name: configure eqemu
        uses: docker/setup-qemu-action@v3
        with:
          platforms: 'linux/arm64,linux/amd64'
      - name: configure docker buildx
        uses: docker/setup-buildx-action@v3
      - name: login to docker registry
        uses: docker/login-action@v3
        with:
          registry: ${{ inputs.registry }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Prepare Bake inputs
        id: docker-bake-inputs
        run: |
          targets=$(docker buildx bake -f docker/docker.hcl --print build | jq -r '.group.build.targets[]')
          input_set=""
          first=0

          EOF=$(dd if=/dev/urandom bs=15 count=1 status=none | base64)

          echo "set<<$EOF" >> "$GITHUB_ENV"
          for target in $targets
          do
              echo "$target.cache-from=type=gha,ignore-error=true,scope=$GITHUB_REF-$target" >> "$GITHUB_ENV"
              echo "$target.cache-to=type=gha,ignore-error=true,mode=max,scope=$GITHUB_REF-$target" >> "$GITHUB_ENV"
          done
          echo "$EOF" >> "$GITHUB_ENV"

      - name: build docker images
        timeout-minutes: 360
        id: docker-bake
        uses: docker/bake-action@v5
        env:
          DOCKER_REGISTRY: ${{ inputs.registry }}/${{ inputs.imageName }}/
          COMMIT_SHA: ${{ inputs.cliVersion }}
          RELEASE: ${{ inputs.cliVersion }}
          BUILD_TYPE: 'publish'
          PWD: ${{ github.workspace }}
        with:
          # See https://github.com/docker/buildx/issues/1533
          provenance: false
          push: true
          files: docker/docker.hcl
          targets: cli
          set: |
            ${{ steps.docker-bake-inputs.outputs.set }}
