#!/bin/bash

set -e

VERSION=$(cat hack/deps/.k8s-version)

# shellcheck disable=SC2207
# Prefer mapfile or read -a to split command output (or quote to avoid splitting)
# TODO: Next author should verify current behavior is correct. If so, keep shellcheck
# disabled, otherwise update according to recommendation
MODS=($(
    curl -sS "https://raw.githubusercontent.com/kubernetes/kubernetes/v${VERSION}/go.mod" |
    sed -n 's|.*k8s.io/\(.*\) => ./staging/src/k8s.io/.*|k8s.io/\1|p'
))

for MOD in "${MODS[@]}"; do
    V=$(
        go mod download -json "${MOD}@kubernetes-${VERSION}" |
        sed -n 's|.*"Version": "\(.*\)".*|\1|p'
    )
    if grep -F "${MOD}" go.mod
    then
        go mod edit "-replace=${MOD}=${MOD}@${V}"
    fi
done
go get "k8s.io/kubernetes@v${VERSION}"