#!/usr/bin/env bash

set -o errexit
set -o nounset
set -o pipefail

ROOT=$(cd $(dirname "${BASH_SOURCE[0]}")/../..; pwd -P)

source $ROOT/hack/lib/vars.sh
source $ROOT/hack/lib/version.sh

# e.g. gcr.io
lib::image::get_image_registry() {
    declare -n _registry=$1

    case $VAR_IMG_HUB in
    ecr)
	    local account=$(aws sts get-caller-identity --query Account --output text)
        _registry="${account}.dkr.ecr.${VAR_AWS_REGION}.amazonaws.com"
        ;;
    acr)
        local acr_repo_name=${ACR_INSTANCE}-registry
        local acr_region="ap-southeast-1"
        # alibabacloud prod use regional vpc registry
        if [ ${VAR_ALIYUN_REGION} == "ap-northeast-1" ] || [ ${VAR_ALIYUN_REGION} == "ap-southeast-5" ]; then
            acr_repo_name=${ACR_INSTANCE}-${VAR_ALIYUN_REGION}-registry-vpc
            acr_region=${VAR_ALIYUN_REGION}
        fi
        _registry="${acr_repo_name}.${acr_region}.cr.aliyuncs.com"
        ;;
    gcr)
        echo "Hub gcr is not supported now"
        exit 1
        ;;
    local)
	    _registry=localhost
        ;;
    pingcap)
	    _registry=hub.pingcap.net
        ;;
    custom)
	    _registry=${VAR_IMG_REGISTRY}
        ;;
    *)
        echo "Unknown image hub: ${VAR_IMG_HUB}"
        echo "Please see ./hack/lib/vars.sh#VAR_IMG_HUB"
        return 1
        ;;
    esac
}

# e.g. library/alpine
lib::image::get_image_repo() {
    declare -n _repo=$1

    local target=${2}
    _repo=${VAR_IMG_PROJECT}/${VAR_IMG_PREFIX}-${target}
}

lib::image::get_image() {
    declare -n _image=$1

    local target=${2}
    local version=${3:-"$VAR_IMG_VERSION"}

    lib::image::get_image_registry registry
    lib::image::get_image_repo repo $target

    if [[ $version == "" ]]; then
        version=$(lib::version::get_image_version)
    fi

    _image=${registry}/${repo}:${version}
}
