function get_oss_bucket_endpoint() {
    oss_path=$1
    bucket_name=${oss_path#oss://}
    bucket_name=${bucket_name%%/*}
    aliyun oss stat oss://$bucket_name | grep "ExtranetEndpoint" | sed -n 's/^ExtranetEndpoint *: *//p'
}

function get_oss_bucket_region() {
    oss_path=$1
    bucket_name=${oss_path#oss://}
    bucket_name=${bucket_name%%/*}
    location=$(aliyun oss stat oss://$bucket_name | grep "Location" | sed -n 's/^Location *: *//p')
    region=${location#oss-}
    echo ${region}
}

function get_cluster_id() {
    cluster_name="$1"
    aliyun cs DescribeClustersV1 --name "$cluster_name" | jq -r '.clusters[0].cluster_id'
}

function get_oidc_arn() {
    cluster_name="$1"
    aliyun cs DescribeClustersV1 --name "$cluster_name" | jq -r '.clusters[0].rrsa_config.oidc_arn'
}

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

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

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

            if [[ "${svc}" == "provider.pkg.crossplane.io/"* ]]; then
                local ready=$(kubectl get ${svc} -ojsonpath='{.status.conditions[?(@.type=="Healthy")].status}' 2>/dev/null)
                if [[ $? -eq 0 ]]; then
                    if [[ "$ready" == "True" ]]; then
                        services_ref[$svc]="true"
                        echo "Service $svc is ready"
                    fi
                fi
            else
                local ready=$(kubectl get ${svc} -n $ns_ref -ojsonpath='{.status.readyReplicas}' 2>/dev/null)
                if [[ $? -eq 0 ]]; then
                    if [[ $ready -ge 1 ]]; then
                        services_ref[$svc]="true"
                        echo "Service $svc in $ns_ref is ready"
                    fi
                fi
            fi
        done

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

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