#!/bin/bash
# Fabric companion — one-paste installer (macOS).
#
# The user downloads fabric-kit-mac.zip in the browser, double-clicks it
# (macOS auto-extracts), then pastes ONE line into Terminal:
#
#     bash ~/Downloads/fabric-kit/install.sh you@yourcompany.com
#
# Why bash-invoked: browser downloads carry the com.apple.quarantine attribute
# and modern macOS (Sequoia+) gives unsigned binaries NO "Open Anyway" shortcut.
# A script run through the interpreter is not gated, and it clears the
# quarantine flag from the kit before anything executes — so Gatekeeper never
# appears in front of the user at all.
set -euo pipefail

KIT="$(cd "$(dirname "$0")" && pwd)"
SELF_ADDR="${1:-}"
# The literal placeholder from START-HERE counts as no address at all.
if [ "$SELF_ADDR" = "you@yourcompany.com" ]; then
  SELF_ADDR=""
fi

echo "Fabric companion — installing from $KIT"

# 0. The binary must exist before anything touches it (a broken unzip or a
#    partial copy should fail with words, not a raw chmod error).
if [ ! -f "$KIT/fabric-collect" ]; then
  echo "✗ fabric-collect is missing from this folder — the kit didn't extract fully."
  echo "  Re-download fabric-kit-mac.zip, double-click it, and paste the same line again."
  exit 1
fi

# 1. Clear quarantine on the whole kit (harmless when absent) + make runnable.
xattr -dr com.apple.quarantine "$KIT" 2>/dev/null || true
chmod +x "$KIT/fabric-collect"

# 2. Sanity: right binary for this machine (kit ships a universal build).
if ! "$KIT/fabric-collect" version >/dev/null 2>&1; then
  echo "✗ The collector binary won't run on this machine. Reply to the message that"
  echo "  brought you this kit with this line:"
  echo "  $(uname -m) / $(sw_vers -productVersion 2>/dev/null || uname -s)"
  exit 1
fi
echo "✓ collector ready ($("$KIT/fabric-collect" version))"

# 3. Hand over. No email argument (the self-serve site path): the collector is
#    installed and Claude drives the rest — go back and continue the setup there.
#    With an email argument (the Thunderbird/M365 route): the guided CLI flow.
if [ -z "$SELF_ADDR" ]; then
  echo ""
  echo "✓ collector ready."
  echo ""
  echo "Go back to Claude and say:  continue my fabric setup"
  echo "It picks up from here, one step at a time."
  echo ""
  exit 0
fi
exec "$KIT/fabric-collect" onboard --self "$SELF_ADDR" --kit "$KIT"
