name: Deflake Tests

# Runs when the Selenum nightly test workflow completes.  This will run with
# full privileges, even if the other workflow doesn't.  That allows us to
# trigger re-runs if we think the results might be flaky.
on:
  workflow_run:
    workflows: [Selenium Lab Tests]
    types: [completed]

jobs:
  deflake:
    if: ${{ github.event.workflow_run.event == 'schedule' && github.event.workflow_run.conclusion == 'failure' }}
    runs-on: ubuntu-latest

    steps:
      - name: Check run count and re-run workflow
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          gh api /repos/${{ github.repository }}/actions/runs/${{ github.event.workflow_run.id }} > run.json
          RUNS=$(jq -r .run_attempt < run.json)
          if [[ "$RUNS" -lt 3 ]]; then
            echo "$RUNS failed runs so far; re-running workflow."
            gh run rerun ${{ github.event.workflow_run.id }} --failed -R ${{ github.repository }}
          else
            echo "$RUNS failed runs so far; not re-running workflow."
          fi
