#!/bin/sh
# Installs foldcard-mcp, Foldcard's MCP server for AI tools on a Mac, and registers it with the AI clients found here
# (Claude Code, Codex, Antigravity, Claude Desktop). Read it before you run it:
#
#   curl -fsSL https://foldcard.groovio.dev/ai/install.sh | sh
#
# It downloads one signed and notarized binary from foldcard.groovio.dev into ~/.local/bin and runs
# `foldcard-mcp install`. `~/.local/bin/foldcard-mcp uninstall` and deleting the file undo it.
set -eu

BASE_URL="${FOLDCARD_BASE_URL:-https://foldcard.groovio.dev/ai}"
BIN_DIR="${FOLDCARD_BIN_DIR:-$HOME/.local/bin}"

fail() {
    printf 'foldcard-mcp: %s\n' "$1" >&2
    exit 1
}

[ "$(uname -s)" = "Darwin" ] || fail "this installer is for macOS only."
case "$(uname -m)" in
    arm64 | x86_64) ;;
    *) fail "unsupported processor $(uname -m)." ;;
esac
major=$(sw_vers -productVersion | cut -d. -f1)
[ "$major" -ge 14 ] || fail "needs macOS 14 or later."

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

printf 'Downloading foldcard-mcp from %s ...\n' "$BASE_URL"
curl -fsSL "$BASE_URL/foldcard-mcp.zip" -o "$work/foldcard-mcp.zip" || fail "the download failed."
ditto -x -k "$work/foldcard-mcp.zip" "$work/unpacked" || fail "the download is not a valid archive."
[ -f "$work/unpacked/foldcard-mcp" ] || fail "the archive holds no foldcard-mcp."

mkdir -p "$BIN_DIR"
mv -f "$work/unpacked/foldcard-mcp" "$BIN_DIR/foldcard-mcp"
chmod 755 "$BIN_DIR/foldcard-mcp"
printf 'Installed %s/foldcard-mcp (%s).\n\n' "$BIN_DIR" "$("$BIN_DIR/foldcard-mcp" --version)"

"$BIN_DIR/foldcard-mcp" install

printf '\nAsk your AI tool for flashcards, for example: "Make a Foldcard deck from this PDF."\n'
printf 'The cards reach Foldcard on your iPhone through iCloud Drive, usually within a minute.\n'
