# shellcheck shell=sh disable=SC3043
# reference https://zhuanlan.zhihu.com/p/90508170
# gem sources --add https://gems.ruby-china.com/ --remove https://rubygems.org/

___x_cmd_mirror_gem(){
    [ "$#" -gt 0 ] ||   set -- --help

    local op="$1"; shift
    case "$op" in
        -h|--help)
            ___x_cmd help -m mirror gem         "$@"
            return   ;;
    esac

    ___x_cmd hascmd gem || N=mirror M="[command=gem] not found." log:ret:1
    case "$op" in
        ls|current|set|unset)  ___x_cmd_mirror_gem_"${op}"  "$@" ;;
        *)                     ___x_cmd_mirror___util_subcmd_invalid gem "$@" ;;
    esac
}

___x_cmd_mirror_gem_ls(){
    printf "%s\n" \
        "Code          Url                                                      Name"              \
        "official      https://rubygems.org                                     官方源"             \
        "ali           https://mirrors.aliyun.com/rubygems/                     阿里云镜像"          \
        "huawei        https://mirrors.huaweicloud.com/repository/rubygems/     华为云镜像"          \
        "tuna          https://mirrors.tuna.tsinghua.edu.cn/rubygems/           清华大学镜像"        \
        "ustc          https://mirrors.ustc.edu.cn/rubygems/                    中国科学技术大学镜像"  \
        "bfsu          https://mirrors.bfsu.edu.cn/rubygems/                    北京外国语大学镜像"
}

___x_cmd_mirror_gem___url(){
    ___x_cmd_mirror_gem_ls | \
        ___x_cmd_mirror___util_get_url_by_name "$1"
}

___x_cmd_mirror_gem_current(){
    gem sources -l | grep "http"
}

___x_cmd_mirror_gem_set() {
    [ "$#" -gt 0 ] ||   set -- ali
    case "$1" in
        -h|--help)
            ___x_cmd help -m mirror gem set "$@"
            return   ;;
    esac

    local url
    url="$(___x_cmd_mirror_gem___url "$1")" || return $?

    mirror:info "Setting gem mirror $url"

    for i in $(___x_cmd_mirror_gem_current); do
        gem sources -r "$i" >/dev/null
    done
    gem sources --add "$url" >/dev/null || {
        mirror:error "Failed to set gem mirror"
        return 1
    }
}

___x_cmd_mirror_gem_unset() {
    ___x_cmd_mirror_gem_set   official
}
