# shellcheck shell=dash

___X_CMD_HOK_SHIMAPP_VERSION='v0.1.0-beta.5'

___x_cmd_hok___check(){
    if ___x_cmd hascmd hok.exe || ___x_cmd hascmd hok; then
        return 0
    else
        local x_=; ___x_cmd_hok___path_shim_ || return
        local binfp="${x_}/hok.exe"
        [ -x "$binfp" ] || return 1
        ___x_cmd path add_existed_folder "$x_"
        return 0
    fi
}

___x_cmd_hok___prepare(){
    ___x_cmd_hok___check || ___x_cmd_hok___install
}

___x_cmd_hok___path_shim_(){
    ___x_cmd_scoop___path_shim_
}

___x_cmd_hok___install(){
    local x_=""
    ___x_cmd os arch_
    local arch="$___X_CMD_OS_ARCH_"

    local pack=;
    case "$arch" in
        x64)    pack="hok-x86_64-pc-windows-msvc.zip"   ;;
        x86)    pack="hok-i686-pc-windows-msvc.zip"     ;;
        arm64)  pack="hok-aarch64-pc-windows-msvc.zip"  ;;
        *)      hok:error "No binary file found for the current [arch=$arch]"
                return 1
                ;;
    esac

    local url;
    if ___x_cmd websrc is cn; then
        url="https://codeberg.org/x-cmd-sourcecode/hok/releases/download/${___X_CMD_HOK_SHIMAPP_VERSION}/${pack}"
    else
        url="https://github.com/chawyehsu/hok/releases/download/${___X_CMD_HOK_SHIMAPP_VERSION}/${pack}"
    fi

    local cachefp="$___X_CMD_ROOT_TMP/hok/cache/$pack";
    ___x_cmd_hok___install_inner "$url" "$cachefp" || return
    ___x_cmd_hok___install_inner "${url}.sha256" "${cachefp}.sha256" || return

    [ "$( ___x_cmd sha256 "$cachefp" )" = "$( ___x_cmd_cmds cat "${cachefp}.sha256" )" ] || {
        hok:error "$cachefp sha256 match fail"
        return 1
    }

    x_=; ___x_cmd_hok___path_shim_ || return
    local binpath="$x_"
    ___x_cmd mkdirp "$binpath"
    ___x_cmd uz "$cachefp" "$binpath" || return
    ___x_cmd_cmds chmod +x "$binpath/hok.exe" || return
    ___x_cmd path add_existed_folder "$binpath"
    ___x_cmd rmrf "$___X_CMD_ROOT_TMP/hok/cache"

    hok:info "Download of hok.exe was successful"
}

___x_cmd_hok___install_inner(){
    local url="$1"
    local cachefp="$2"
    ___x_cmd rmrf "$cachefp";   ___x_cmd ensurefp "$cachefp"
    hok:info --url "$url" --cachefp "$cachefp" "Downloading"
    ___x_cmd curl -s -L -o "$cachefp" "$url" || {
        printf "\r\n" >&2
        hok:error "Download failed"
        return 1
    }
}

