# Copyright VMware, Inc.
# SPDX-License-Identifier: APACHE-2.0

---
name: '[License] Check license headers'
on:
  pull_request_target:
    types:
      - opened
      - synchronize
    branches:
      - main
      - bitnami:main
# Remove all permissions by default
permissions: {}
jobs:
  license-headers-linter:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
    steps:
      - uses: actions/checkout@v3
        name: Checkout Repository
        with:
          ref: ${{ github.event.pull_request.head.ref }}
          repository: ${{ github.event.pull_request.head.repo.full_name }}
      - id: get-modified-files
        name: 'Get modified files'
        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)"
          dockerfiles=()
          while read -r file_changed; do
            # Avoid removed files
            if [[ -f "${file_changed}" ]]; then
              dockerfiles+=("${file_changed}")
            fi
          done <<< "$(echo "$files_changed" | grep -oE ".*/Dockerfile$" | sort | uniq || true)"
          if [[ ${#dockerfiles[@]} -gt 0 ]]; then
            # There are modifications on dockerfiles
            export dockerfiles_json=$(printf "%s\n" "${dockerfiles[@]}" | jq -R . | jq -cs .)
            # Overwrite configuration file to analyze only changed dockerfiles
            yq -i '. | .header.paths=env(dockerfiles_json)' .licenserc.yaml
            echo "result=success" >> $GITHUB_OUTPUT
          else
            echo "result=skip" >> $GITHUB_OUTPUT
          fi
      - name: Check license Headers
        uses: apache/skywalking-eyes/header@v0.4.0
        if: ${{ steps.get-modified-files.outputs.result == 'success' }}