#
# Copyright Super iPaaS Integration LLC, an IBM Company 2024
#
#!/bin/bash

pr_number_to_check=$1
Auth_Token=$2
echo "The triggering pull request number is: $pr_number_to_check"

max_overall_duration=3600  # 1 hour in seconds
start_overall_time=$(date +%s)

# Keep checking for one hour
while true; do

    has_p1_label=$(curl -s --request GET \
    --url "https://github.webmethods.io/api/v3/repos/AIM/api-studio/pulls/$pr_number_to_check" \
    --header "Authorization: Bearer $Auth_Token" | jq -r '.labels[] | select(.name == "P1")')

    if [ -n "$has_p1_label" ]; then
        echo "The current pull request has the 'P1' label."
        echo "Checking for any other priority pull request are open..."

        previous_prior_prs=$(curl -s --request GET \
            --url "https://github.webmethods.io/api/v3/repos/AIM/api-studio/pulls?state=open" \
            --header "Authorization: Bearer $Auth_Token" | jq -r '.[] | select(.labels[].name == "P1") | .number | select(. < '$pr_number_to_check')')

        if [ "$(echo "$previous_prior_prs" | wc -l)" -eq 1 ]; then
        previous_prior_prs="$previous_prior_prs"
        else
            previous_prior_prs=$(echo "$previous_prior_prs" | sort -n)
        fi

        # Check if the triggering pull request was the only open pull request
        if [ -z "$previous_prior_prs" ]; then
            echo "The current pull request is $pr_number_to_check, there are no other open priority pull requests."
            echo "Hence continuing to the next job..."
            break
        fi

        while true; do
            all_closed=true
            for pr_number in $previous_prior_prs; do
                pr_state=$(curl -s --request GET \
                    --url "https://github.webmethods.io/api/v3/repos/AIM/api-studio/pulls/$pr_number" \
                    --header "Authorization: Bearer $Auth_Token" | jq -r '.state')

                if [ "$pr_state" != "closed" ]; then
                    all_closed=false
                    break
                fi
            done

            if $all_closed; then
                echo "All pull requests are closed."
                break
            else
                echo "Not all pull requests are closed. Checking again in 30 seconds..."
                sleep 30
            fi
        done



    else
        upcoming_prior_prs=$(curl -s --request GET \
            --url "https://github.swebmethods.io/api/v3/repos/AIM/api-studio/pulls?state=open" \
            --header "Authorization: Bearer $Auth_Token" | jq -r '.[] | select(.labels[].name == "P1") | .number | select(. > '$pr_number_to_check')')

        while true; do
            all_closed=true
            for pr_number in $upcoming_prior_prs; do
                pr_state=$(curl -s --request GET \
                    --url "https://github.webmethods.io/api/v3/repos/AIM/api-studio/pulls/$pr_number" \
                    --header "Authorization: Bearer $Auth_Token" | jq -r '.state')

                if [ "$pr_state" != "closed" ]; then
                    all_closed=false
                    break
                fi
            done

            if $all_closed; then
                echo "All pull requests are closed."
                break
            else
                echo "Not all pull requests are closed. Checking again in 30 seconds..."
                sleep 30
            fi
        done


        # Flag to track if any pull request meets the criteria
        any_pull_request_meets_criteria=false

        # Fetch the list of open pull requests excluding the triggering pull request
        open_prs=$(curl -s --request GET \
            --url "https://github.webmethods.io/api/v3/repos/AIM/api-studio/pulls?state=open" \
            --header "Authorization: Bearer $Auth_Token" | jq -r '.[]."number" | select(. < '$pr_number_to_check')')

        # Check if there's only one pull request number
        if [ "$(echo "$open_prs" | wc -l)" -eq 1 ]; then
            open_prs="$open_prs"
        else
            open_prs=$(echo "$open_prs" | sort -n)
        fi

        # Check if the triggering pull request was the only open pull request
        if [ -z "$open_prs" ]; then
            echo "The current pull request is $pr_number_to_check, there are no other open pull requests."
            echo "Hence continuing to the next job..."
            break
        fi

        # Iterate through open pull requests and find the earliest one
        for open_pr_number in $open_prs; do
            echo "Checking pull request number: $open_pr_number"

            pr_state=""
            pr_draft=""
            reviews=""

            # Fetch the state, draft status, and approval status of the open pull request
            sleep 10  # Wait for 10 seconds before checking again
            pr_info=$(curl -s --request GET \
                --url "https://github.webmethods.io/api/v3/repos/AIM/api-studio/pulls/$open_pr_number" \
                --header "Authorization: Bearer $Auth_Token" | jq -r '.state, .draft')

            # reviews=$(curl -s --request GET \
            #     --url "https://github.softwareag.com/api/v3/repos/AIM/api-cloud-ct/pulls/$open_pr_number/reviews" \
            #     --header "Authorization: Bearer $Auth_Token" | jq -r '.[].state')
            reviews=$(curl -s --request GET \
                --url "https://github.webmethods.io/api/v3/repos/AIM/api-studio/pulls/$open_pr_number/reviews" \
                --header "Authorization: Bearer $Auth_Token")
            approved_reviews=$(echo "$reviews" | jq '[ .[] | select(.state == "APPROVED") ] | length')

            pr_state=$(echo "$pr_info" | awk 'NR==1')
            pr_draft=$(curl -s --request GET \
                --url "https://github.webmethods.io/api/v3/repos/AIM/api-studio/issues/$open_pr_number/labels" \
                --header "Authorization: Bearer $Auth_Token"  | jq 'map(select(.name == "draft")) | length > 0' )

            echo "Pull Request State: $pr_state"
            echo "Draft Status: $pr_draft"
            echo $approved_reviews

            if [ "$pr_state" != "null" ]; then
                echo "The open pull request $open_pr_number is in state: $pr_state."
               if [ "$pr_state" = "open" ] && [ "$pr_draft" = "false" ]; then
                    if [ "$approved_reviews" -ge 2 ]; then
                        echo "The pull request $open_pr_number is open, not in draft state, and has at least two approvals."
                        echo "No need for further validation.."
                        any_pull_request_meets_criteria=true
                        break
                    else
                        echo "The pull request $open_pr_number is open, not in draft state, but does not have at least two approvals."
                    fi
                else
                    echo "The pull request $open_pr_number is not open or is in draft state."
                fi
            else
                echo "No pull request information found for pull request $open_pr_number."
            fi
        done


        echo $any_pull_request_meets_criteria
        # Check if any pull request meets the criteria
        if [ "$any_pull_request_meets_criteria" = false ]; then
            break
        fi

        # Check overall duration
        current_overall_time=$(date +%s)
        elapsed_overall_time=$((current_overall_time - start_overall_time))

        if [ "$elapsed_overall_time" -gt "$max_overall_duration" ]; then
            echo "Tried for 1 hour on all open pull requests."
            break
        fi

        # Wait for 30 seconds before checking again for a new set of pull requests
        echo "Waiting for 30 seconds before checking again."
        sleep 30
    fi
done
