#!/usr/bin/env bash
# Ensure a runnable Ollama binary exists at <nexus_root>/ollama/bin/ollama.
#
# ollama/ is gitignored, so a `git clone` checkout has no binary — download the
# official Linux x86-64 build (pinned to the version the native box ships) so
# clone installs are self-sufficient. A folder-copy install already has the
# binary and this is a no-op. Single source of the pinned version for both
# bin/restore-linux.sh (the desktop stage of a restore).
#
#   fetch-ollama.sh <nexus_root>
#   NEXUS_OLLAMA_VERSION=vX.Y.Z fetch-ollama.sh <nexus_root>   # override pin

set -euo pipefail

root="${1:?usage: fetch-ollama.sh <nexus_root>}"
bin="$root/ollama/bin/ollama"
version="${NEXUS_OLLAMA_VERSION:-v0.21.1}"

# Already present and runnable → nothing to do.
if [ -x "$bin" ] && "$bin" --version &>/dev/null; then
    exit 0
fi

case "$(uname -m)" in
    x86_64|amd64) ;;
    *)
        echo "ERROR: Ollama download supports x86-64 only (detected $(uname -m))." >&2
        exit 1
        ;;
esac

# ponytail: stock amd64 asset ships CPU + CUDA runners, not ROCm. An AMD/ROCm
# box wanting GPU offload needs the `-rocm` asset; the CPU runner works meanwhile
# (the native box runs num_gpu=0 anyway). Swap the asset name if that changes.
echo "Ollama binary missing — downloading $version..."
url="https://github.com/ollama/ollama/releases/download/${version}/ollama-linux-amd64.tar.zst"
tmp="$(mktemp)"
trap 'rm -f "$tmp"' EXIT

curl -fSL --retry 3 -o "$tmp" "$url" \
    || { echo "ERROR: could not download Ollama from $url" >&2; exit 1; }
mkdir -p "$root/ollama"
tar --zstd -xf "$tmp" -C "$root/ollama" \
    || { echo "ERROR: could not extract Ollama tarball (need zstd + tar --zstd)." >&2; exit 1; }

chmod +x "$bin" 2>/dev/null || true
"$bin" --version &>/dev/null \
    || { echo "ERROR: downloaded Ollama could not run (expected x86-64 at $bin)." >&2; exit 1; }
echo "Ollama $version ready."
