#!/usr/bin/env sh
set -eu

# Synapse MCP installer.
# Downloads the precompiled launcher for this platform.
#
# SECURITY NOTE: integrity here relies on HTTPS transport security only
# (curl/wget over TLS) — there is no signature verification of the
# downloaded binary in this script. The launcher itself already trusts a
# pinned Ed25519 public key to verify signed manifests for the Elixir
# runtime it decrypts (see release_manifest.rs); the same verification
# should eventually also cover the launcher binary this script installs,
# most practically by having the freshly-installed binary verify its own
# signature against that manifest as part of its first run, reusing
# whichever verification code the launcher's self-upgrade feature adds,
# rather than reimplementing Ed25519 verification in POSIX shell here.
#
# Override:
#   SYNAPSE_MCP_VERSION=v0.1.0
#   SYNAPSE_MCP_BASE_URL=https://downloads.synapse-mcp.dev/synapse-mcp
#   SYNAPSE_MCP_INSTALL_DIR=$HOME/.local/bin
#   SYNAPSE_MCP_PLATFORM=linux-x86_64

VERSION="${SYNAPSE_MCP_VERSION:-latest}"
BASE_URL="${SYNAPSE_MCP_BASE_URL:-${SYNAPSE_MCP_BASE_URL:-https://downloads.synapse-mcp.dev/synapse-mcp}}"
INSTALL_DIR="${SYNAPSE_MCP_INSTALL_DIR:-$HOME/.local/bin}"
BIN_NAME="synapse-mcp"


uname_s=$(uname -s | tr '[:upper:]' '[:lower:]')
uname_m=$(uname -m)

case "$uname_s:$uname_m" in
  linux:x86_64|linux:amd64) platform="linux-x86_64" ;;
  linux:aarch64|linux:arm64) platform="linux-aarch64" ;;
  darwin:x86_64) platform="darwin-x86_64" ;;
  darwin:arm64|darwin:aarch64) platform="darwin-aarch64" ;;
  msys*:x86_64|mingw*:x86_64|cygwin*:x86_64) platform="windows-x86_64.exe" ;;
  *) echo "Unsupported platform: $uname_s/$uname_m" >&2; exit 1 ;;
esac

platform="${SYNAPSE_MCP_PLATFORM:-$platform}"
artifact="${BIN_NAME}-${platform}"
url="${BASE_URL}/${VERSION}/${artifact}"

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

mkdir -p "$INSTALL_DIR"
printf 'Downloading %s\n' "$url" >&2

if command -v curl >/dev/null 2>&1; then
  curl -fL --retry 3 --connect-timeout 20 "$url" -o "$tmp"
elif command -v wget >/dev/null 2>&1; then
  wget -O "$tmp" "$url"
else
  echo "Install requires curl or wget" >&2
  exit 1
fi

chmod 0755 "$tmp"
install_path="$INSTALL_DIR/$BIN_NAME"
if [ "${platform#*.}" = "exe" ]; then
  install_path="$INSTALL_DIR/$BIN_NAME.exe"
fi
mv "$tmp" "$install_path"

cat >&2 <<EOF
Installed $BIN_NAME to $install_path

Next steps:
  1. Add $INSTALL_DIR to PATH if needed.
  2. Run: synapse-mcp install
EOF
