# Copyright Broadcom, Inc. All Rights Reserved.
# SPDX-License-Identifier: APACHE-2.0

name: '[Support] Assign asset label'
on:
  pull_request_target:
    types:
      - opened
# Remove all permissions by default
permissions: {}
jobs:
  assign-label:
    name: Assign label
    runs-on: ubuntu-latest
    permissions:
      pull-requests: write
    steps:
      - id: get-asset
        name: Get modified assets
        env:
          DIFF_URL: "${{github.event.pull_request.diff_url}}"
          TEMP_FILE: "${{runner.temp}}/pr-${{github.event.number}}.diff"
        run: |
          # This request doesn't consume API calls.
          curl -Lkso $TEMP_FILE $DIFF_URL
          files_changed="$(sed -nr 's/[\-\+]{3} [ab]\/(.*)/\1/p' $TEMP_FILE | sort | uniq)"
          # Adding || true to avoid "Process exited with code 1" errors
          assets=($(echo "$files_changed" | xargs dirname | sed -nr "s|bitnami/([^/]*).*|\1|p" | sort | uniq || true))

          if [[ "${#assets[@]}" -ne "1" ]]; then
            echo "result=skip" >> $GITHUB_OUTPUT
            echo "message=Label cannot be set, cannot infer a single label from: ${assets[@]}" >> $GITHUB_OUTPUT
            echo "name=NONE" >> $GITHUB_OUTPUT
          else
            echo "result=ok" >> $GITHUB_OUTPUT
            echo "message=Adding label '${assets}'" >> $GITHUB_OUTPUT
            echo "name=${assets}" >> $GITHUB_OUTPUT
          fi
      - name: Show messages
        uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd
        with:
          script: |
            if ("${{ steps.get-asset.outputs.result }}" != "ok" ) {
              core.warning("${{ steps.get-asset.outputs.message }}")
            } else {
              core.info("${{ steps.get-asset.outputs.message }}")
            }
      - name: Labeling
        if: ${{ steps.get-asset.outputs.result == 'ok' }}
        uses: fmulero/labeler@d3ef0aadb212cd1656bd6d5ce1e772787bf1682b
        with:
          add-labels: "${{ steps.get-asset.outputs.name }}"
