#!/bin/sh
# Installs botdb: curl -fsSL botdb.dev/install.sh | sh
# Set BOTDB_INSTALL_DIR to choose where the binary goes (default: ~/.local/bin).
set -eu

base="${BOTDB_DOWNLOAD_URL:-https://botdb.dev/dl}"
dir="${BOTDB_INSTALL_DIR:-$HOME/.local/bin}"

case "$(uname -s)-$(uname -m)" in
  Darwin-arm64) target=aarch64-apple-darwin ;;
  Linux-x86_64 | Linux-amd64) target=x86_64-unknown-linux-musl ;;
  Linux-aarch64 | Linux-arm64) target=aarch64-unknown-linux-musl ;;
  *)
    echo "botdb: no prebuilt binary for $(uname -s) $(uname -m) yet." >&2
    echo "Build it from source with Rust: cargo install --git https://github.com/vimtor/botdb botdb-cli" >&2
    exit 1
    ;;
esac

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT INT TERM

echo "Downloading botdb for $target..."
curl -fsSL "$base/botdb-$target.tar.gz" -o "$tmp/botdb.tar.gz"
curl -fsSL "$base/SHA256SUMS" -o "$tmp/SHA256SUMS"

expected=$(grep "botdb-$target.tar.gz" "$tmp/SHA256SUMS" | cut -d' ' -f1)
if command -v sha256sum >/dev/null 2>&1; then
  actual=$(sha256sum "$tmp/botdb.tar.gz" | cut -d' ' -f1)
else
  actual=$(shasum -a 256 "$tmp/botdb.tar.gz" | cut -d' ' -f1)
fi
if [ -z "$expected" ] || [ "$expected" != "$actual" ]; then
  echo "botdb: checksum mismatch, not installing" >&2
  exit 1
fi

tar -xzf "$tmp/botdb.tar.gz" -C "$tmp"
mkdir -p "$dir"
mv "$tmp/botdb" "$dir/botdb"
chmod +x "$dir/botdb"
echo "Installed $("$dir/botdb" --version) to $dir/botdb"

case ":$PATH:" in
  *":$dir:"*) ;;
  *) echo "Add $dir to your PATH, e.g.: echo 'export PATH=\"$dir:\$PATH\"' >> ~/.profile" ;;
esac

echo
echo "Next: botdb login          # vault, recovery phrase and a free botdb cloud account"
echo "      botdb create movies  # then: botdb sql \"CREATE TABLE ...\""
echo "      botdb mcp install    # connect your agents"
