#!/usr/bin/env bash
set -euo pipefail

destination="${HOME}/.local/share/sshmcp/releases/5.1.1"
if [[ ${1:-} == --prefix && $# == 2 ]]; then
  destination=$2
elif [[ $# != 0 ]]; then
  printf 'Usage: bash install.sh [--prefix /absolute/path]\n' >&2
  exit 2
fi
[[ $destination == /* ]] || { printf 'Destination must be absolute\n' >&2; exit 2; }
package_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
(cd "$package_dir" && sha256sum -c SHA256SUMS)
umask 077
mkdir -p "$destination"
# Version directories are immutable: an upgrade must never truncate a running binary.
for name in mcp-ssh-manager sshmcp-file-agent; do
  if [[ -e "$destination/$name" ]]; then
    cmp -s "$package_dir/$name" "$destination/$name" || { printf 'Existing file differs: %s\n' "$destination/$name" >&2; exit 1; }
  else
    install -m 700 "$package_dir/$name" "$destination/$name"
  fi
done
"$destination/mcp-ssh-manager" --version
printf 'executable=%s\nhelper=%s\n' "$destination/mcp-ssh-manager" "$destination/sshmcp-file-agent"
printf 'Files installed. Follow docs/INSTALL.md to connect your existing MCP client.\n'
