#!/bin/sh
# Installs the Inferam CLI. Source: https://inferam.ai/install
set -eu
# Everything runs from main, so a download cut off mid-script runs nothing.
main() {
base="${INFERAM_RELEASES:-https://inferam.ai/releases}"
dir="${INFERAM_INSTALL_DIR:-$HOME/.local/bin}"
fail() { echo "inferam install: $*" >&2; exit 1; }

case "$(uname -s)" in Darwin) os=darwin ;; Linux) os=linux ;; *) fail "unsupported OS: $(uname -s)" ;; esac
case "$(uname -m)" in x86_64 | amd64) arch=amd64 ;; arm64 | aarch64) arch=arm64 ;; *) fail "unsupported CPU: $(uname -m)" ;; esac
file="inferam_${os}_${arch}"

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
curl -fsSL -o "$tmp/inferam" "$base/$file" || fail "download failed"
curl -fsSL -o "$tmp/checksums.txt" "$base/checksums.txt" || fail "checksum download failed"
want=$(awk -v f="$file" '$2 == f { print $1 }' "$tmp/checksums.txt")
if command -v sha256sum >/dev/null 2>&1; then got=$(sha256sum "$tmp/inferam" | cut -d' ' -f1)
else got=$(shasum -a 256 "$tmp/inferam" | cut -d' ' -f1); fi
[ -n "$want" ] && [ "$want" = "$got" ] || fail "checksum mismatch for $file"

mkdir -p "$dir"
chmod 755 "$tmp/inferam"
mv "$tmp/inferam" "$dir/inferam"
echo "Installed $("$dir/inferam" version) to $dir/inferam"
case ":$PATH:" in
  *":$dir:"*) ;;
  *) echo "Add it to your PATH:  export PATH=\"$dir:\$PATH\"" ;;
esac
echo "Next: inferam auth login"
}
main "$@"
