# shellcheck shell=dash

___x_cmd log init clear

___x_cmd_clear___main(){
    local version="${1}";
    [ -n "$version" ] || N=x M="Please provide the x-cmd version" log:ret:64
    local codedir="$___X_CMD_ROOT/v/$version"
    [ -d "$codedir" ] || {
        x:info "Not found x-cmd [version=$version] code in the current environment"
        return 0
    }

    case "$version" in
        alpha|beta|latest)
            local old_version="$version"
            local old_codedir="$codedir"
            local x_file="$codedir/X"
            local line1=; local line2=
            { read -r line1 && read -r line2;  } < "$x_file"
            local new_version="${line2#"___X_CMD_VERSION="}"
            [ -n "$new_version" ] || return
            x:info "The corresponding version for x-cmd's $old_version is -> $new_version"
            version="$new_version"
            codedir="$___X_CMD_ROOT/v/$version"

            if [ ! -d "$codedir" ]; then
                x:info "The code for x-cmd [version=$new_version] no longer exists"
                ___x_cmd rmrf "$old_codedir"
                return 0
            fi
            ;;
    esac

    x:info "Attempting to remove the code for x-cmd [version=$version] -> x rmrf $codedir"
    if [ "$version" != "$___X_CMD_VERSION" ]; then
        x:warn "If other shells are using this version, they may be affected."
        if ___x_cmd ui yesno -r "Do you want to remove the code for x-cmd [version=$version] -> x rmrf $codedir"; then
            ___x_cmd rmrf "$codedir"
        fi
    else
        x:warn "The current shell is using x-cmd with [version=$version]. If deleted, it won't function well"
        local id=
        ___x_cmd ui select id \
            "Do you want to remove the code for x-cmd [version=$version] -> x rmrf $codedir" \
            "Later, I will do it by myself (RECOMMENDED)" \
            "Just remove the code for x-cmd [version=$version]" \
            "Remove the code for x-cmd [version=$version] and EXIT the current shell"

        case "$id" in
            1)  return 0 ;;
            2)  ___x_cmd rmrf "$codedir" ;;
            3)  ___x_cmd rmrf "$codedir"; exit 0 ;;
        esac
    fi
}


