name: '[Support] Update README metadata'

on:
  pull_request_target:
    branches:
      - main
    paths:
      - 'bitnami/*/values.yaml'
permissions:
  contents: write
jobs:
  update-readme-metadata:
    runs-on: ubuntu-latest

    steps:
      - name: Install readme-generator-for-helm
        run: npm install -g @bitnami/readme-generator-for-helm@2.4.2
      - name: Checkout bitnami/charts
        uses: actions/checkout@v3
        with:
          ref: ${{github.event.pull_request.head.ref}}
          repository: ${{github.event.pull_request.head.repo.full_name}}
          path: charts
          token: ${{ github.actor == 'bitnami-bot' && secrets.GITHUB_TOKEN || secrets.BITNAMI_BOT_TOKEN }}
      - name: Execute readme-generator-for-helm
        run: |
          # Using the Github API to detect the files changed as git merge-base stops working when the branch is behind
          # and jitterbit/get-changed-files does not support pull_request_target
          URL="https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/files"
          files_changed_data=$(curl -s --header 'authorization: Bearer ${{ secrets.GITHUB_TOKEN }}' -X GET -G "$URL")
          files_changed="$(echo $files_changed_data | jq -r '.[] | .filename')"
          # Adding || true to avoid "Process exited with code 1" errors
          charts_dirs_changed="$(echo "$files_changed" | xargs dirname | grep -o "bitnami/[^/]*" | sort | uniq || true)"
          for chart in ${charts_dirs_changed}; do
            echo "Updating README.md for ${chart}"
            readme-generator --values "charts/${chart}/values.yaml" --readme "charts/${chart}/README.md" --schema "/tmp/schema.json"
          done
      - name: Push changes
        run: |
          # Push all the changes
          cd charts
          if git status -s | grep bitnami; then
            git config user.name "Bitnami Containers"
            git config user.email "bitnami-bot@vmware.com"
            git add . && git commit -am "Update README.md with readme-generator-for-helm" --signoff && git push
          fi
