name: Approve GH Workflows

on:
  pull_request_target:
    types:
      - labeled
      - synchronize
    branches:
      - master

jobs:
  approve:
    name: Approve ok-to-test
    if: contains(github.event.pull_request.labels.*.name, 'ok-to-test')
    runs-on: ubuntu-latest
    permissions:
      actions: write
    steps:
      - name: Update PR
        uses: actions/github-script@d7906e4ad0b1822421a7e6a35d5ca353c962f410 # v6.4.1
        continue-on-error: true
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          debug: ${{ secrets.ACTIONS_RUNNER_DEBUG == 'true' }}
          script: |
            const result = await github.rest.actions.listWorkflowRunsForRepo({
              owner: context.repo.owner,
              repo: context.repo.repo,
              event: "pull_request",
              status: "action_required",
              head_sha: context.payload.pull_request.head.sha,
              per_page: 100
            });

            for (var run of result.data.workflow_runs) {
              await github.rest.actions.approveWorkflowRun({
                owner: context.repo.owner,
                repo: context.repo.repo,
                run_id: run.id
              });
            }
