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

            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
        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
}
