#!/bin/bash

function wait_workflow_run_to_merge() {
    set +e # Ignore error when gh command fails
    local workflow="$1"
    local repo="$2"
    local timeout="${3:-3600}"  # Default to 1 hour
    local interval="${4:-10}"  # Default to 10 seconds

    sleep 10 # hack: gh don't support output the run id yet, simply wait for the workflow.
    # Get the run ID of the most recent workflow run
    run_id=$(gh run list --workflow "$workflow" --repo "$repo" --json 'databaseId' --jq '.[0].databaseId')
    echo "run_id: $run_id"
    gh run watch "$run_id" --repo "$repo" --interval $interval --exit-status
    if [[ $? -ne 0 ]]; then
        echo "workflow run $run_id failed"
        return 1
    fi

    # Extract PR number from the run log
    pr_number=$(gh run view "$run_id" --repo "$repo" --log | grep -o 'pull-request-number: [0-9]\+' | head -n 1 | sed 's/pull-request-number: //')
    if [[ -z "$pr_number" ]]; then
        echo "No pr is created, assume it's merged"
        return 0
    fi
    echo "PR number: $pr_number"


    # Wait for PR to be merged
    start_time=$(date +%s)
    while [[ $(($(date +%s) - start_time)) -lt $timeout ]]; do
        pr_status=$(gh pr view "$pr_number" --repo "$repo" --json 'state' --jq '.state')
        if [[ $pr_status == "MERGED" ]]; then
            echo "PR number $pr_number is merged"
            return 0
        fi
        sleep "$interval"
    done

    echo "Timeout waiting for PR $pr_number to be merged"
    return 1
}

function wait_for_services_ready() {
    set +e # Ignore error when kubectl command fails

    local -n services="$1"
    local timeout="${JOB_TIMEOUT:-600}"  # 10 mins
    local interval="${JOB_CHECK_INTERVAL:-10}"

    echo "waiting for services ready"

    start_time=$(date +%s)
    while [[ $(($(date +%s) - $start_time)) -lt $timeout ]]; do
        all_ready=true
        for svc in "${!services[@]}"; do
            if [[ ${services[$svc]} == "true" ]]; then
                continue
            else
                all_ready=false
            fi

            ready=$(kubectl get ${svc} -ojsonpath='{.status.readyReplicas}' 2>/dev/null)
            if [[ $? -eq 0 ]]; then
                if [[ $ready -ge 1 ]]; then
                    services[$svc]="true"
                    echo "Service $svc is ready"
                fi
            fi
        done

        if $all_ready; then
            echo "All services ready!"
            return 0
        else
            sleep "$interval"
        fi
    done

    # Report unready services
    echo "Following services are unready:"
    for svc in "${!services[@]}"; do
        if [[ ${services[$svc]} == "false" ]]; then
            echo $svc
        fi
    done
    return 1
}

function eks_exists() {
    local cluster_name="$1"
    local region="$2"
    local profile="$3"

    if aws eks describe-cluster --profile=$profile --name "$cluster_name" --region "$region" >/dev/null 2>&1; then
        return 0
    else
        return 1
    fi
}

function setup_o11y_deploy_profile() {
    local o11y_role_arn=$1
    cat <<EOF >> ~/.aws/config

[profile o11y-deploy]
source_profile=default
role_arn=$o11y_role_arn
EOF
}
