#!/bin/sh
# Installs the ogm CLI — Open God Mode, the open-weights LLM tracker.
#
#   curl -fsSL https://opengodmode.ai/install.sh | sh
#
# Options (environment variables):
#   OGM_INSTALL_DIR  target directory (default: /usr/local/bin if writable,
#                    otherwise ~/.local/bin, created if needed)
#   OGM_BASE_URL     alternate download host (default: the site this script
#                    was published from)
#
# Prebuilt binaries: linux/darwin x amd64/arm64. Checksums are verified.
set -eu

BASE="${OGM_BASE_URL:-https://opengodmode.ai}"

os=$(uname -s | tr '[:upper:]' '[:lower:]')
arch=$(uname -m)
case "$os" in
  linux | darwin) ;;
  *)
    echo "ogm install: unsupported OS '$os' (linux and macOS only)" >&2
    exit 1
    ;;
esac
case "$arch" in
  x86_64 | amd64) arch=amd64 ;;
  aarch64 | arm64) arch=arm64 ;;
  *)
    echo "ogm install: unsupported architecture '$arch' (amd64 and arm64 only)" >&2
    exit 1
    ;;
esac

asset="ogm_${os}_${arch}.gz"
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT INT TERM

fetch() {
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$1" -o "$2"
  elif command -v wget >/dev/null 2>&1; then
    wget -qO "$2" "$1"
  else
    echo "ogm install: need curl or wget" >&2
    exit 1
  fi
}

echo "downloading $BASE/dl/$asset"
fetch "$BASE/dl/$asset" "$tmp/$asset"
fetch "$BASE/dl/checksums.txt" "$tmp/checksums.txt"

want=$(awk -v a="$asset" '$2 == a { print $1 }' "$tmp/checksums.txt")
if command -v sha256sum >/dev/null 2>&1; then
  got=$(sha256sum "$tmp/$asset" | awk '{ print $1 }')
else
  got=$(shasum -a 256 "$tmp/$asset" | awk '{ print $1 }')
fi
if [ -z "$want" ] || [ "$want" != "$got" ]; then
  echo "ogm install: checksum mismatch for $asset (want ${want:-unknown}, got $got)" >&2
  exit 1
fi

gunzip -c "$tmp/$asset" >"$tmp/ogm"
chmod +x "$tmp/ogm"

dir="${OGM_INSTALL_DIR:-}"
if [ -z "$dir" ]; then
  if [ -d /usr/local/bin ] && [ -w /usr/local/bin ]; then
    dir=/usr/local/bin
  else
    dir="$HOME/.local/bin"
  fi
fi
mkdir -p "$dir"
mv "$tmp/ogm" "$dir/ogm"

echo "installed $("$dir/ogm" --version) to $dir/ogm"
case ":$PATH:" in
  *":$dir:"*) ;;
  *) echo "note: $dir is not in PATH — add it with: export PATH=\"$dir:\$PATH\"" ;;
esac
