run-name: Cleanup ${{ github.head_ref }}
on:
  pull_request_target:
    types: labeled
    paths:
      - 'images/**'

jobs:
  clean_ci:
    name: Clean CI runs
    runs-on: ubuntu-latest
    permissions:
      actions: write
    steps:
      - env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        shell: pwsh
        run: |
          $startDate = Get-Date -UFormat %s
          $workflows = @("macos11", "macos12", "ubuntu2004", "ubuntu2204", "windows2019", "windows2022")
          while ($true) {
            $continue = $false
            foreach ($wf in $workflows) {
              $skippedCommand = "gh run list --workflow ${wf}.yml --branch ${{ github.event.pull_request.head.ref }} --repo ${{ github.repository }} --status skipped --json databaseId"
              $skippedIds = Invoke-Expression -Command $skippedCommand | ConvertFrom-Json | ForEach-Object { $_.databaseId }
              $skippedIds | ForEach-Object {
                $deleteCommand = "gh run delete --repo ${{ github.repository }} $_"
                Invoke-Expression -Command $deleteCommand
              }
              $pendingCommand = "gh run list --workflow ${wf}.yml --branch ${{ github.event.pull_request.head.ref }} --repo ${{ github.repository }} --status requested --json databaseId --template '{{ . | len }}'"
              $pending = Invoke-Expression -Command $pendingCommand
              if ($pending -gt 0) {
                Write-Host "Pending for ${wf}.yml: $pending run(s)"
                $continue = $true
              }
            }
            if ($continue -eq $false) {
              Write-Host "All done, exiting"
              break
            }
            $curDate = Get-Date -UFormat %s
            if (($curDate - $startDate) -gt 60) {
              Write-Host "Reached timeout, exiting"
              break
            }
            Write-Host "Waiting 5 seconds..."
            Start-Sleep -Seconds 5
          }
