# shellcheck shell=dash
___x_cmd_pkg_env_upgrade(){
    local ___X_CMD_PKG_ENV_LOG_MOD="${___X_CMD_PKG_ENV_LOG_MOD:-"pkg"}"
    local X_help_cmd="___x_cmd help -m ${___X_CMD_PKG_ENV_LOG_MOD} upgrade"
    ___x_cmd_pkg_env_upgrade___inner "$@"
}


___x_cmd_pkg_env_upgrade___inner_option(){
    while [ "$#" -gt 0 ]; do
        case "$1" in
            --all)                      upgrade_all=1 ;;
            --latest|--default)         upgrade_target="${1#--}" ;;
            --force-recycle|--force)    XPKG_ENV_UPGRADE_FORCE_RECYCLE=1
        esac
        shift
    done
}

___x_cmd_pkg_env_upgrade___inner(){
    local X_help_cmd="${X_help_cmd:-"___x_cmd help -m pkg upgrade"}"
    pkg:sphere:parse:option
    sphere_name="${sphere_name:-X}"
    [ "$#" -gt 0 ] || {
        eval "$X_help_cmd" >&2; return 64
    }

    local name=; local version=;
    local upgrade_all=
    local upgrade_target="default"
    local XPKG_ENV_UPGRADE_FORCE_RECYCLE="$XPKG_ENV_UPGRADE_FORCE_RECYCLE"
    ___x_cmd_pkg_env_upgrade___inner_option "$@"
    if [ -n "$upgrade_all" ]; then
        pkg:info "Upgrading all used pkg to the ${upgrade_target} version"
        ___x_cmd_pkg_sphere_use upgrade_all \
            --sphere "$sphere_name" --sphereroot "$___X_CMD_PKG_ROOT_SPHERE" \
            --osarch "$osarch" "$upgrade_target"
        return
    fi

    while [ "$#" -gt 0 ]; do
        case "$1" in
            --all|--latest|--default|--force-recycle|--force)
                    shift; continue ;;
            *=*)    name="${1%=*}"; version="${1#*=}" ;;
            *)      name="$1";      version=""
                    ;;
        esac
        ___x_cmd_pkg_sphere_use upgrade_pkg \
            --sphere "$sphere_name" --sphereroot "$___X_CMD_PKG_ROOT_SPHERE" \
            --osarch "$osarch" "$name" "$version" "$upgrade_target" || return $?
        shift
    done
}

