#!/bin/sh
# NVCL AI: the NVCL inference engine on this machine (Linux x86-64 with an NVIDIA GPU, or a Mac with Apple Silicon),
# a model, and an OpenAI-compatible endpoint, in one command. Free for personal use.
#
#   curl -fsSL https://get.nvcl.ai/install.sh | sh                             the menu: choose a model and install it
#   curl -fsSL https://get.nvcl.ai/install.sh | sh -s -- --yes                 the defaults, no questions
#   curl -fsSL https://get.nvcl.ai/install.sh | sh -s -- --yes --model qwen3.8-27b --port 8000 --public
#   wget -qO- https://get.nvcl.ai/install.sh | sh                              the same without curl
#   curl -fsSL https://mirror.downloads.nvcl.ai/install.sh | sh                 the same file from our mirror in Moscow
#
# This script only puts the nvcl-ai binary of the site's latest release (cli/nvcl-ai/latest.json: its path and sha256)
# in NVCL_BIN (default ~/.local/bin) and runs it with the terminal: in a terminal and without arguments the menu
# (`nvcl-ai`), whose "Install a ready model" installs one; otherwise `nvcl-ai install` with its arguments. nvcl-ai does
# the rest (`nvcl-ai --help`). No sudo here. NVCL_AI_NO_INSTALL=1 only installs the binary.
# The site is get.nvcl.ai. From Russia Cloudflare cuts connections after ~16 KB: a machine Cloudflare places there
# (loc=RU in its trace, a few hundred bytes, which still pass), or one our API does not answer at all, starts on our
# mirror in Moscow (what runs on an A100 or a Tesla A2); elsewhere the mirror is taken when get.nvcl.ai stalls or fails
# from here. NVCL_SITE names the site and skips the other; NVCL_MIRROR names another mirror (`-`: none).
# The same file for every release: it is published as it is.
set -eu

MAIN=https://get.nvcl.ai
MIRROR=${NVCL_MIRROR:-https://mirror.downloads.nvcl.ai}
MIRROR=${MIRROR%/}
TRACE=https://api.nvcl.ai/cdn-cgi/trace
BIN=${NVCL_BIN:-$HOME/.local/bin}

say() { printf '%s\n' "$*"; }
fail() { printf 'nvcl-ai install: %s\n' "$*" >&2; exit 1; }
has() { command -v "$1" >/dev/null 2>&1; }
fetch() {  # URL FILE RETRIES: a connection under 10 KB/s for 20 s is dropped (wget: one that sends nothing for 20 s)
  if has curl; then curl -fsSL --retry "$3" --retry-delay 2 --connect-timeout 20 --speed-limit 10240 --speed-time 20 \
    -o "$2" "$1"
  else wget -q --tries=$(($3 + 1)) --timeout=20 -O "$2" "$1"; fi
}
sha256() { if has sha256sum; then sha256sum "$1"; else shasum -a 256 "$1"; fi | cut -d' ' -f1; }
through_mirror() {  # whether to start on the mirror, and why: Cloudflare places this machine in Russia, or our API
  # does not answer within 5 s (an answer of any status is one: wget's 8)
  if has curl; then TRACED=$(curl -sS --max-time 5 "$TRACE" 2>/dev/null) || { say "api.nvcl.ai does not answer"; return 0; }
  else TRACED=$(wget -qO- --tries=1 --timeout=5 "$TRACE" 2>/dev/null) || [ $? = 8 ] ||
    { say "api.nvcl.ai does not answer"; return 0; }; fi
  printf '%s\n' "$TRACED" | grep -qx 'loc=RU' && say "From Russia"
}

has curl || has wget || fail "needs curl or wget"
has sha256sum || has shasum || fail "needs sha256sum or shasum"
OS=$(uname -s) ARCH=$(uname -m)
if [ "$OS" = Darwin ] && [ "$(sysctl -n hw.optional.arm64 2>/dev/null)" = 1 ]; then ARCH=arm64; fi  # not Rosetta's
case "$OS-$ARCH" in
  Linux-x86_64) PLATFORM=linux-x86_64 ;;
  Darwin-arm64) PLATFORM=darwin-arm64 ;;
  *) fail "this machine is $OS $ARCH: nvcl-ai runs on Linux x86-64 or a Mac with Apple Silicon" ;;
esac

mkdir -p "$BIN" 2>/dev/null && [ -w "$BIN" ] || fail "cannot write to $BIN: NVCL_BIN=<a folder of yours> installs there"
TMP=$BIN/.nvcl-ai-install.$$
trap 'rm -f "$TMP" "$TMP.json"' EXIT
trap 'exit 130' HUP INT TERM
# latest.json as `nvcl-publish site` writes it (one key per line); only the characters a version, a path or a sha256 has
pick() { sed -n "$1" "$TMP.json" | head -n 1; }
release() {  # SITE RETRIES: SITE's latest nvcl-ai for this machine in $TMP, checked; else WHY and 1
  fetch "$1/cli/nvcl-ai/latest.json" "$TMP.json" "$2" || { WHY="cannot download $1/cli/nvcl-ai/latest.json"; return 1; }
  VERSION=$(pick 's|^ *"version": *"\([0-9A-Za-z.+-]*\)",*$|\1|p')
  FILE=$(pick "/\"$PLATFORM\": *{/,/}/s|^ *\"path\": *\"\([0-9A-Za-z._+/-]*\)\",*\$|\1|p")
  SHA=$(pick "/\"$PLATFORM\": *{/,/}/s|^ *\"sha256\": *\"\([0-9a-f]*\)\",*\$|\1|p")
  [ -n "$VERSION" ] && [ -n "$FILE" ] && [ ${#SHA} = 64 ] ||
    { WHY="$1 has no nvcl-ai release for $PLATFORM"; return 1; }
  say "• Downloading nvcl-ai $VERSION ($PLATFORM) from $1"
  fetch "$1/$FILE" "$TMP" "$2" || { WHY="cannot download $1/$FILE"; return 1; }
  [ "$(sha256 "$TMP")" = "$SHA" ] || { WHY="checksum mismatch: $1/$FILE (nothing installed)"; return 1; }
}
if [ -n "${NVCL_SITE:-}" ]; then
  release "${NVCL_SITE%/}" 5 || fail "$WHY"
elif [ "$MIRROR" != - ] && WHY=$(through_mirror); then
  say "• $WHY: our mirror in Moscow"
  if ! release "$MIRROR" 2; then
    say "  $WHY: $MAIN"
    release "$MAIN" 5 || fail "$WHY"
  fi
elif ! release "$MAIN" 1; then
  [ "$MIRROR" != - ] || fail "$WHY"
  say "  $MAIN stalls or fails from here ($WHY): our mirror in Moscow"
  release "$MIRROR" 5 || fail "$WHY"
  # nvcl-ai up to 0.5.9 knows no mirror: its run takes the catalog and models from it (later ones switch themselves)
  case "$VERSION" in 0.[0-4].*|0.5.[0-9]) export NVCL_SITE=$MIRROR ;; esac
fi
chmod 755 "$TMP"
mv -f "$TMP" "$BIN/nvcl-ai"

say "✓ nvcl-ai $VERSION is installed: $BIN/nvcl-ai"
case ":$PATH:" in
  *":$BIN:"*) ;;
  *) say "  Add it to PATH:  export PATH=\"$BIN:\$PATH\"  (in ~/.bashrc or ~/.zshrc)" ;;
esac
if [ "${NVCL_AI_NO_INSTALL:-}" = 1 ]; then
  say "Next: $BIN/nvcl-ai install"
  exit 0
fi
say ""
rm -f "$TMP" "$TMP.json"  # exec skips the EXIT trap
trap - EXIT
# In a terminal and without arguments: the menu. With arguments, or without a terminal: `nvcl-ai install` with them,
# which asks its questions on the terminal. When this script comes through a pipe, its stdin is the script itself: the
# terminal is /dev/tty.
if [ -t 0 ]; then
  if [ $# = 0 ] && [ -t 1 ]; then exec "$BIN/nvcl-ai"; fi
  exec "$BIN/nvcl-ai" install "$@"
elif (exec </dev/tty) 2>/dev/null; then
  if [ $# = 0 ] && [ -t 1 ]; then exec "$BIN/nvcl-ai" </dev/tty; fi
  exec "$BIN/nvcl-ai" install "$@" </dev/tty
else
  exec "$BIN/nvcl-ai" install "$@" </dev/null  # no terminal: nvcl-ai takes the defaults and says so
fi
