# shellcheck    shell=dash disable=SC2010
___x_cmd_pkg__smoke()(
    ___x_cmd_pkg_osarch_ || return $?
    local candidate; candidate="$1"
    local version="$2"; [ -n "$version" ] || {
        local x_=; ___x_cmd_pkg_default_version_ "$candidate" "$___X_CMD_PKG_OSARCH" || return $?
        version="$x_"
    }
    local sphere_name="X"

    pkg:info "Smoke testing candidate=$candidate version=$version"

    pkg:info "Step1 => Checking the active version of $candidate"
    if ! ___x_cmd env try "$candidate"="$version"; then
        pkg:error "Smoke FAIL. Failed to set $candidate=$version"
        return 11
    fi

    pkg:info "Step2 => Checking the install path of $candidate $version"
    local bin_path=; local bin_name=; local cur=; local tgt=;
    local x_treename=; ___x_cmd_pkg_treename_ "$candidate" "$version" "$___X_CMD_PKG_OSARCH" || return $?
    tgt="$___X_CMD_PKG_ROOT_SPHERE/$sphere_name/$x_treename/$candidate/$version"
    ___x_cmd_pkg_sphere_link list_all_path_expand "$candidate" "$version" "$___X_CMD_PKG_OSARCH" "$tgt" bin app | while ___x_cmd_readr bin_path; do
        [ -n "$bin_path" ] || continue
        [ -f "$bin_path" ] || {
            pkg:error "Not found $bin_path for $candidate $version bin link"
            return 1
        }

        bin_name="${bin_path##*/}"
        pkg:debug "_smoke bin_name: [$bin_name]"
        bin_suffix="${bin_name#*.}"
        ! [ "$bin_suffix" = "conf" ] || continue
        ! [ "$bin_suffix" = "cmd" ] || continue
        [ "${___X_CMD_PKG_OSARCH%/*}" = "win" ] || {
            ! [ "$bin_suffix" = "bat" ] || continue
        }

        unset -f "$bin_name" 2>/dev/null || true
        unalias "$bin_name" 2>/dev/null || true
        cur="$(command -v "$bin_name")"
        if [ -z "$bin_path" ]; then
            pkg:error "Smoke FAIL. $candidate $version is not installed, command -v $bin_name returned empty"
            return 12
        fi

        local expected_prefix="$___X_CMD_PKG_ROOT_SPHERE/$sphere_name/$x_treename/$candidate"
        if [  "${cur#"$expected_prefix"}" = "$cur" ] || ! ( printf "%s" "$cur" | command grep -q "$version") ; then
            pkg:error "Smoke FAIL. $candidate $version is not installed in $expected_prefix or $cur does not contain $version"
            return 12
        fi
    done

    pkg:info "Step3 => Checking the smoke of $candidate $version"
    local smokepath; smokepath=$(___x_cmd_cmds_ls "$___X_CMD_PKG_METADATA_PATH"/*"/$candidate/.x-cmd/smoke.sh") 2>/dev/null
    if ! [ -f "$smokepath" ] || ! . "$smokepath"; then
        pkg:error "Smoke FAIL. Smoke file not found or returned exit code candidate=$candidate version=$version smokepath=$smokepath"
        ! [ -f "$smokepath" ] || {
            ___x_cmd rat "$smokepath"
            pkg:error "Smoke FAIL. smoke file end"
        }
        return 13
    fi

    pkg:info "Smoke PASS. $candidate $version "
) >&2

#TODO: remove tobe_remove
