# Copyright 2020 Google LLC

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     https://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

on:
  pull_request:

name: auto-approve

jobs:
  approve:
    runs-on: ubuntu-latest
    if: contains(github.head_ref, 'autosynth')
    steps:
      - uses: actions/github-script@0.9.0
        with:
          github-token: ${{secrets.YOSHI_APPROVER_TOKEN}}
          script: |
            // only approve PRs from yoshi-automation user
            if (context.payload.sender.login != "yoshi-automation") {
              console.log("skipping: not from yoshi-automation")
              return;
            }
            // only approve PRs like "Autogenerated update"
            if (!context.payload.pull_request.title.startsWith("Autogenerated update")) {
              console.log("skipping: not an autogenerated update")
              return;
            }
            // approve the PR
            await github.pulls.createReview({
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: 'Rubber stamped client regeneration!',
              pull_number: context.payload.pull_request.number,
              event: 'APPROVE'
            });
            // add the "automerge" label
            await github.issues.addLabels({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.payload.pull_request.number,
              labels: ["automerge"]
            });
            console.log("Done.")
