name: Update README metadata

on:
  pull_request_target:
    branches:
      - master
    paths:
      - 'bitnami/*/values.yaml'

jobs:
  update-readme-metadata:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout bitnami-labs/readme-generator-for-helm
        uses: actions/checkout@v2
        with:
          repository: 'bitnami-labs/readme-generator-for-helm'
          ref: '1af12881436b1f58f0643d733fd5196b4a11caa8'
          path: readme-generator-for-helm

      - name: Cache node modules
        uses: actions/cache@v2
        env:
          cache-name: cache-node-modules
        with:
          # npm cache files are stored in `~/.npm` on Linux/macOS
          path: ~/.npm
          key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('readme-generator-for-helm/package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-build-${{ env.cache-name }}-

      - name: Install readme-generator-for-helm dependencies
        run: cd readme-generator-for-helm && npm install

      - name: Checkout bitnami/charts
        uses: actions/checkout@v2
        with:
          ref: ${{github.event.pull_request.head.ref}}
          repository: ${{github.event.pull_request.head.repo.full_name}}
          path: charts
          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-for-helm/bin/index.js --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 "containers@bitnami.com"
            git add . && git commit -am "Update README.md with readme-generator-for-helm" --signoff && git push
          fi
