#!/bin/sh
# MCP Desk bridge installer for macOS and Linux.
#
#   curl -fsSL https://mcpdesk.ai/install.sh | sh
#
# The bridge runs in a container (the image docker.io/mcpdesk/bridge from Docker Hub) and nowhere else: no program of MCP Desk is
# installed on this computer outside the container, and no helper script stays on it. The bridge tries a direct path to the desk
# and otherwise uses MCP Desk's encrypted relay, which always works. It also adds a folder for your files, the workspace (MCPDeskFiles in your home folder): it is the only folder the container can see, and where
# the AI's file transfers (push_file, pull_file) go.
#
# What it does
#   1. Reads the current release number from https://mcpdesk.ai/downloads/latest/VERSION and downloads, from that exact
#      release folder (never "latest"), the helper script and its doctor into a temporary folder, with the SHA256SUMS file.
#   2. Checks the SHA-256 of both files. If one does not match, nothing is run.
#   3. Runs the helper from the temporary folder and deletes the folder when it ends. The helper:
#        - finds Podman or Docker (Docker Desktop too); when neither is installed it installs one (Podman, or Docker Desktop
#          on an Intel Mac) and starts it. That is the only thing this installer installs;
#        - pulls the pinned image by digest, signs the bridge in inside a short-lived container (it opens the browser once,
#          unless a setup code was given), starts the container "mcpdesk-bridge" (it comes back after a restart);
#        - points Claude Code, Codex, Cursor, Claude Desktop and Grok at it: each runs
#          "<runtime> exec -i mcpdesk-bridge /mcpdeskagent bridge" (every changed file is copied first);
#        - makes the workspace folder ~/MCPDeskFiles when it is missing and gives the container that one folder (at /workspace
#          in it), never your home folder itself and never a second folder; uninstall leaves it and its files;
#        - removes what an earlier installer left: the native bridge (background service, Claude Code session hook, the
#          program in ~/.local/bin when only the bridge used it) and the helper files in ~/.local/bin. A desk agent on this
#          computer (the program that lets it be controlled) is never touched.
#          Anything else an older installer of ours added is removed too (only after the new container is healthy).
#      If the container cannot be made it says why and exits with an error; there is no native fallback, and whatever was
#      installed before is left working.
#
# Running it again is safe: it repairs or updates whatever it finds and says what it did.
#
# Options
#   Arguments go to the helper (an action first, "install" when there is none):
#     curl -fsSL https://mcpdesk.ai/install.sh | sh -s -- --dry-run
#     curl -fsSL https://mcpdesk.ai/install.sh | sh -s -- status
#     curl -fsSL https://mcpdesk.ai/install.sh | sh -s -- --help    (printed by this script itself, nothing is downloaded)
#     actions: install | status | update | uninstall [--purge] | start | stop | login | logs | measure | pair ... | fallback ...
#     --runtime podman|docker | --port N | --no-clients | --no-handover | --no-autostart | --dry-run
#     --timeout <seconds>      how long the sign-in waits for you to press Allow (30 to 3600, default 900 = 15 minutes)
#     --callback-port <port>   the local port the browser sign-in reply comes back to (1024 to 65535)
#     --workspace <folder>     the ONE folder the container may read and write (default ~/MCPDeskFiles; not your home folder or
#                              a folder above it); --no-workspace shares no folder; both also with update
#   Environment variables:
#     MCPDESK_WORKSPACE=<folder|none> the same as --workspace / --no-workspace (the option wins)
#     MCPDESK_LOGIN_TIMEOUT=<seconds> the same as --timeout (the option wins)
#     MCPDESK_LOGIN_PORT=<port>       the same as --callback-port (the option wins)
#     MCPDESK_BRIDGE_RUNTIME=podman|docker  use this runtime only
#     MCPDESK_INSTALL_DIR=<dir>       where an EARLIER installer put its files (default $HOME/.local/bin); only looked at to
#                                     remove them
#
# Setup code (optional)
#   Your AI client may give a one-time setup code (works once) in front of "sh". This script passes the
#   environment on untouched; the helper takes the code out of the environment first thing. A code your AI client got
#   for its own word of your yes signs nothing in until you press Allow on the MCP Desk page it named; the installer
#   waits for that (see --timeout) and needs no browser on this computer.
#
# Uninstall
#   curl -fsSL https://mcpdesk.ai/install.sh | sh -s -- uninstall      (add --purge to delete the container's data volume)
#   By hand: docker rm -f mcpdesk-bridge   (or: podman rm -f mcpdesk-bridge), then put each AI client file back from the
#   copy next to it (<file>.mcpdesk-backup-<time>); the sign-in is in the volume: docker volume rm mcpdesk-bridge-data

# Piped to zsh instead of sh (`curl ... | zsh`), zsh would not split unquoted words and would run the script wrongly: read it as sh.
if [ -n "${ZSH_VERSION:-}" ]; then emulate sh; fi

set -eu

BASE_DEFAULT="https://mcpdesk.ai/downloads"
# downloaded to a temporary folder and run from there; nothing is copied anywhere else
FILES="mcpdesk-bridge mcpdesk-bridge-doctor"
tmp=""

say() { printf 'mcpdesk: %s\n' "$*"; }
die() { printf 'mcpdesk: error: %s (exit 1)\n' "$*" >&2; exit 1; }

cleanup() {
  [ -z "$tmp" ] || rm -rf "$tmp"
  tmp=""
}

have() { command -v "$1" >/dev/null 2>&1; }

# fetch <url> <output file>
fetch() {
  if have curl; then
    curl -fsSL --connect-timeout 20 --retry 2 -o "$2" "$1" || die "download failed: $1"
  else
    wget -q -O "$2" "$1" || die "download failed: $1"
  fi
}

sha256_of() {
  if have sha256sum; then
    sha256sum "$1" | awk '{print $1}'
  elif have shasum; then
    shasum -a 256 "$1" | awk '{print $1}'
  elif have openssl; then
    openssl dgst -sha256 "$1" | awk '{print $NF}'
  else
    die "need sha256sum, shasum or openssl to verify the download"
  fi
}

# check_sum <SHA256SUMS> <asset name> <file>
check_sum() {
  count=$(awk -v n="$2" '$2 == n || $2 == "*" n { c++ } END { print c + 0 }' "$1")
  [ "$count" = 1 ] || die "SHA256SUMS lists $2 $count times (expected once)"
  expected=$(awk -v n="$2" '$2 == n || $2 == "*" n { print $1 }' "$1")
  printf '%s\n' "$expected" | grep -Eq '^[0-9A-Fa-f]{64}$' || die "SHA256SUMS has an invalid hash for $2"
  expected=$(printf '%s' "$expected" | tr 'A-F' 'a-f')
  actual=$(sha256_of "$3")
  [ "$actual" = "$expected" ] || die "checksum mismatch for $2 (expected $expected, got $actual); nothing was installed"
}

usage() {
  cat <<'USAGE'
mcpdesk.ai bridge installer: runs the bridge in a container (Podman or Docker) and points your AI clients at it.
Nothing of MCP Desk is installed on this computer; only a container runtime, when there is none.

  curl -fsSL https://mcpdesk.ai/install.sh | sh                           install, or repair (safe to run again)
  curl -fsSL https://mcpdesk.ai/install.sh | sh -s -- <action> [options]

actions:  install (default) | status | update | uninstall [--purge] | start | stop | login | logs | measure
options:  --dry-run  --quiet  --runtime podman|docker  --port N  --no-clients  --no-handover  --no-autostart
          --timeout <seconds>  --callback-port <port>
status exits 0 when the bridge is healthy, 3 when it is signed out.
More: https://mcpdesk.ai
USAGE
}

main() {
  # help alone is answered here, before anything is downloaded
  if [ $# -eq 1 ]; then
    case "$1" in -h | --help) usage; exit 0 ;; esac
  fi
  base="${MCPDESK_INSTALL_BASE:-$BASE_DEFAULT}"
  [ -n "${HOME:-}" ] || die "HOME is not set"

  case "$(uname -s)" in
    Darwin | Linux) ;;
    *) die "unsupported system $(uname -s); this installer supports macOS and Linux (Windows: irm https://mcpdesk.ai/install.ps1 | iex)" ;;
  esac
  case "$(uname -m)" in
    x86_64 | amd64 | aarch64 | arm64) ;;
    *) die "unsupported CPU $(uname -m); supported: x86_64, aarch64" ;;
  esac
  if ! have curl && ! have wget; then
    die "need curl or wget"
  fi

  trap cleanup EXIT
  trap 'exit 1' HUP INT TERM
  tmp=$(umask 077; mktemp -d "${TMPDIR:-/tmp}/mcpdesk-install.XXXXXX") || die "cannot create a temporary folder"

  fetch "$base/latest/VERSION" "$tmp/VERSION"
  version=$(tr -d '\r' < "$tmp/VERSION")
  case "$version" in
    '' | *[!0-9.]*) die "the release number from $base/latest/VERSION is not valid" ;;
  esac
  printf '%s\n' "$version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$' || die "the release number from $base/latest/VERSION is not valid"

  say "MCP Desk bridge $version: it runs in a container; no program of MCP Desk is installed on this computer outside it"
  if [ "${MCPDESK_ALLOW_TEST_OVERRIDES:-}" = 1 ] && [ -n "${MCPDESK_HELPER_DIR:-}" ]; then
    say "TEST OVERRIDES ARE ON"
    for f in $FILES; do
      cp "$MCPDESK_HELPER_DIR/$f.sh" "$tmp/$f" || die "no $f.sh in $MCPDESK_HELPER_DIR"
    done
  else
    fetch "$base/$version/SHA256SUMS" "$tmp/SHA256SUMS"
    for f in $FILES; do
      fetch "$base/$version/$f.sh" "$tmp/$f"
      check_sum "$tmp/SHA256SUMS" "$f.sh" "$tmp/$f"
    done
    say "checksums OK"
  fi
  # A helper published before the container-only installer would install a native bridge and files in ~/.local/bin: never run it.
  grep -q '^CONTAINER_ONLY=1$' "$tmp/mcpdesk-bridge" \
    || die "release $version was published before the container-only installer (its helper would install a native bridge); nothing was changed. Try again after the next release"
  chmod 700 "$tmp/mcpdesk-bridge" "$tmp/mcpdesk-bridge-doctor"

  # The helper runs from the temporary folder (questions, if any, are asked on the terminal itself, never on this script's
  # input), is told which release it came from, and gets the setup code and every other variable unchanged. Its exit code is
  # this script's; the folder is deleted either way.
  rc=0
  MCPDESK_RELEASE_VERSION="$version" /bin/sh "$tmp/mcpdesk-bridge" "$@" < /dev/null || rc=$?
  cleanup
  exit "$rc"
}

main "$@"
