#!/bin/sh
# DocuFind installer: downloads the signed binary, checks its checksum, installs it to
# ~/.docufind-mcp/bin/docufind and runs `docufind setup` (models, indexing, background helper,
# Claude registration). Arguments are passed to setup, e.g. folders to index:
#
#   curl -fsSL https://twokeyllc.com/docufind/install.sh | sh
#   curl -fsSL https://twokeyllc.com/docufind/install.sh | sh -s -- ~/Documents ~/Dropbox
set -eu

BASE="${DOCUFIND_BASE_URL:-https://twokeyllc.com/docufind/downloads}"
DEST="$HOME/.docufind-mcp/bin"

fail() { echo "docufind: $*" >&2; exit 1; }

[ "$(uname -s)" = "Darwin" ] || fail "DocuFind runs on macOS only."
[ "$(uname -m)" = "arm64" ] || fail "DocuFind needs a Mac with Apple silicon (M1 or later)."

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

echo "Downloading DocuFind..."
curl -fsSL "$BASE/docufind-macos-arm64.zip" -o "$tmp/docufind.zip" || fail "download failed"
curl -fsSL "$BASE/SHA256SUMS" -o "$tmp/SHA256SUMS" || fail "download failed"
expected=$(awk '$2 == "docufind-macos-arm64.zip" { print $1 }' "$tmp/SHA256SUMS")
actual=$(shasum -a 256 "$tmp/docufind.zip" | awk '{ print $1 }')
[ -n "$expected" ] && [ "$expected" = "$actual" ] || fail "checksum mismatch; not installing"

ditto -x -k "$tmp/docufind.zip" "$tmp/x"
mkdir -p "$DEST"
mv -f "$tmp/x/bin/docufind" "$DEST/docufind"
chmod 755 "$DEST/docufind"
echo "Installed $DEST/docufind ($("$DEST/docufind" --version))"

"$DEST/docufind" setup "$@"

case ":$PATH:" in
  *":$DEST:"*) ;;
  *) echo
     echo "To run docufind from a terminal, add it to your PATH:"
     echo "  echo 'export PATH=\"\$HOME/.docufind-mcp/bin:\$PATH\"' >> ~/.zshrc" ;;
esac
