# Copyright Broadcom, Inc. All Rights Reserved.
# SPDX-License-Identifier: APACHE-2.0

name: '[CI/CD] Retry release PRs'
on:
  schedule:
    # Every 2 hours
    - cron: '0 */2 * * *'
# Remove all permissions by default
permissions: {}
jobs:
  retry-failed-pr-releases:
    runs-on: ubuntu-latest
    permissions:
      actions: write
    if: ${{ github.repository_owner == 'bitnami' }}
    steps:
      - name: Retry "CI Pipeline" failed runs in releases PRs
        env:
          MAX_RETRY_SLOTS: 15
          MAX_RUNS_ATTEMPTS: ${{vars.MAX_RUNS_ATTEMPTS}}
          TEMP_FILE: "${{runner.temp}}/failed_runs.json"
          WORKFLOW_RUNS_URL: "${{ github.api_url }}/repos/${{ github.repository }}/actions/workflows/35553382/runs"
          TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          # Obtain "CI Pipeline" failed runs executed by the bitnami-bot and filter those from release PRs with $MAX_RUNS_ATTEMPTS or more attempts
          curl -X GET -GLkso "${TEMP_FILE}" "${WORKFLOW_RUNS_URL}" \
            -d "status=failure" -d "actor=bitnami-bot" -d "created=>$(date -d '-3 day' '+%Y-%m-%d')" -d "per_page=100"
          readarray -t retriable_runs_ids < <(jq --argjson runs ${MAX_RUNS_ATTEMPTS} \
            '.workflow_runs[] | select((.run_attempt < $runs) and (.display_title | contains("Update dependency references"))).id' "${TEMP_FILE}")

          echo "Found ${#retriable_runs_ids[@]} failed runs that need to be retried"
          if [[ ${#retriable_runs_ids[@]} -gt ${MAX_RETRY_SLOTS} ]]; then
            echo "To avoid potential overload issues in CP, only ${MAX_RETRY_SLOTS} runs will be retried in this cron execution"
          fi

          for run_id in "${retriable_runs_ids[@]:0:${MAX_RETRY_SLOTS}}"; do
            echo "Retrying workflow $(jq --argjson id $run_id '.workflow_runs[] | select(.id==$id) | .html_url' ${TEMP_FILE})"
            rerun_url=$(jq -r --argjson id $run_id '.workflow_runs[] | select(.id==$id) | .rerun_url' "${TEMP_FILE}")
            curl -H "Authorization: Bearer ${TOKEN}" -X POST -Lks ${rerun_url}
          done
