# shellcheck shell=dash

___x_cmd_ollama___install(){
    ! ___x_cmd hasbin ollama || return 0
    local x_
    ___x_cmd os name_
    case "$x_" in
        linux|darwin)   "___x_cmd_ollama___install_${x_}"                 ;;
        *)              N=ollama M="Unsupported [os=$x_]" log:ret:64      ;;
    esac
}

___x_cmd_ollama___install_linux(){
    (
        ___x_cmd hasbin curl || ___x_cmd env try curl
        ___x_cmd curl -fsSL https://ollama.com/install.sh | sh
    )
}

___x_cmd_ollama___install_darwin(){
    ollama:info "Installing Ollama"
    local dst="/Applications/Ollama.app"
    local ollama_tmp="$___X_CMD_ROOT_TMP/ollama"
    local zip_path="$ollama_tmp/Ollama-darwin.$$.zip"

    ___x_cmd mkdirp "$ollama_tmp" || return 1

    ! [ -d "$dst" ] || {
        ___x_cmd ui yesno "Ollama is already installed. Do you want to reinstall it?" || return 0
        ___x_cmd rmrf "$dst"
    }

    ___x_cmd curl -# -fL https://ollama.com/download/Ollama-darwin.zip > "$zip_path" || {
        ollama:error "Failed to download Ollama."
        ___x_cmd rmrf "$zip_path"
        return 1
    }

    ___x_cmd uz "$zip_path" "$ollama_tmp" || {
        ollama:error "Failed to extract Ollama."
        ___x_cmd rmrf "$zip_path" "$ollama_tmp/Ollama.app"
        return 1
    }

    ___x_cmd rmrf "$zip_path"
    ___x_cmd mv "$ollama_tmp/Ollama.app" "$dst" || {
        ollama:error "Failed to move Ollama to Applications."
        ___x_cmd rmrf "$ollama_tmp/Ollama.app" "$dst"
        return 1
    }

    ollama:info "Successfully installed Ollama, you can now run it from the Applications folder."
}

___x_cmd_ollama___install_win(){
    ollama:warn "x-cmd does not currently support Ollama on Windows"
    ollama:info " You can download it yourself for Windows: https://github.com/ollama/ollama?tab=readme-ov-file"
}
