#
# DO NOT EDIT THIS FILE
#
# It is automatically copied from https://github.com/pion/.goassets repository.
# If this repository should have package specific CI config,
# remove the repository name from .goassets/.github/workflows/assets-sync.yml.
#
# If you want to update the shared CI config, send a PR to
# https://github.com/pion/.goassets instead of this repository.
#

name: generate-authors

on:
  pull_request:

jobs:
  checksecret:
    runs-on: ubuntu-latest
    outputs:
      is_PIONBOT_PRIVATE_KEY_set: ${{ steps.checksecret_job.outputs.is_PIONBOT_PRIVATE_KEY_set }}
    steps:
      - id: checksecret_job
        env:
          PIONBOT_PRIVATE_KEY: ${{ secrets.PIONBOT_PRIVATE_KEY }}
        run: |
          echo "is_PIONBOT_PRIVATE_KEY_set: ${{ env.PIONBOT_PRIVATE_KEY != '' }}"
          echo "::set-output name=is_PIONBOT_PRIVATE_KEY_set::${{ env.PIONBOT_PRIVATE_KEY != '' }}"

  generate-authors:
    needs: [checksecret]
    if: needs.checksecret.outputs.is_PIONBOT_PRIVATE_KEY_set == 'true'
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
      with:
        ref: ${{ github.head_ref }}
        fetch-depth: 0
        token: ${{ secrets.PIONBOT_PRIVATE_KEY }}

    - name: Generate the authors file
      run: .github/generate-authors.sh

    - name: Add the authors file to git
      run: git add AUTHORS.txt

    - name: Get last commit message
      id: last-commit-message
      run: |
        COMMIT_MSG=$(git log -1 --pretty=%B)
        COMMIT_MSG="${COMMIT_MSG//'%'/'%25'}"
        COMMIT_MSG="${COMMIT_MSG//$'\n'/'%0A'}"
        COMMIT_MSG="${COMMIT_MSG//$'\r'/'%0D'}"
        echo "::set-output name=msg::$COMMIT_MSG"

    - name: Get last commit author
      id: last-commit-author
      run: |
        echo "::set-output name=msg::$(git log -1 --pretty='%aN <%ae>')"

    - name: Check if AUTHORS.txt file has changed
      id: git-status-output
      run: |
        echo "::set-output name=msg::$(git status -s | wc -l)"

    - name: Commit and push
      if: ${{ steps.git-status-output.outputs.msg != '0' }}
      run: |
        git config user.email $(echo "${{ steps.last-commit-author.outputs.msg }}" | sed 's/\(.\+\) <\(\S\+\)>/\2/')
        git config user.name $(echo "${{ steps.last-commit-author.outputs.msg }}" | sed 's/\(.\+\) <\(\S\+\)>/\1/')
        git add AUTHORS.txt
        git commit --amend --no-edit
        git push --force https://github.com/${GITHUB_REPOSITORY} $(git symbolic-ref -q --short HEAD)
