name: Cleanup caches for closed PRs

on:
  # Run twice every day to remove the cache so that the caches from the closed prs
  # are removed.
  schedule:
    - cron: "0 17 * * *"
    - cron: "30 18 * * *"
  workflow_dispatch:

jobs:
  cleanup:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Cleanup
        run: |
          set -euxo pipefail

          gh extension install actions/gh-actions-cache

          export REPO="${{ github.repository }}"

          # Setting this to not fail the workflow while deleting cache keys.
          set +e

          # Remove pull requests cache, since they cannot be reused
          gh pr list --state closed -L 20 --json number --jq '.[]|.number' | (
              while IFS='$\n' read -r closed_pr; do
                  BRANCH="refs/pull/${closed_pr}/merge" ./cleanup-cache.sh
              done
          )
          # Remove merge queue cache, since they cannot be reused
          gh actions-cache list -L 100 | cut -f 3 | (grep 'gh-readonly-queue' || true) | sort -u | (
              while IFS='$\n' read -r branch; do
                  BRANCH="$branch" ./cleanup-cache.sh
              done
          )
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}