#!/bin/sh
# Bellpip installer: curl -fsSL https://bellpip.com/install.sh | sh
# Downloads Bellpip.app, checks its SHA-256, installs it to /Applications (or ~/Applications) and opens it.
# Read it first: curl -fsSL https://bellpip.com/install.sh | less
#
# Test overrides (not for normal use): BELLPIP_URL (the zip; its checksum is "$BELLPIP_URL.sha256"),
# BELLPIP_DEST (the folder Bellpip.app goes into), BELLPIP_EDITOR_ARGS (extra arguments for the editors' CLIs, e.g.
# "--user-data-dir X --extensions-dir Y" to install into a scratch profile instead of yours).
#
# Everything runs inside main(), called on the last line, so a download cut off halfway runs nothing.

set -eu

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

check_mac() {
  [ "$(uname -s)" = Darwin ] || die "Bellpip is a Mac app. This computer runs $(uname -s), not macOS."
  ver=$(sw_vers -productVersion)
  major=${ver%%.*}
  [ "$major" -ge 14 ] 2>/dev/null ||
    die "Bellpip needs macOS 14 (Sonoma) or newer. This Mac runs macOS $ver. Update macOS in System Settings > General > Software Update."
  # uname -m says x86_64 in a Rosetta shell on Apple Silicon; hw.optional.arm64 tells the truth.
  [ "$(sysctl -n hw.optional.arm64 2>/dev/null || echo 0)" = 1 ] ||
    die "Bellpip needs a Mac with Apple silicon (M1 or newer). This Mac has an Intel processor, which Bellpip does not support yet."
}

download() { # url file [progress]
  if [ "${3:-}" = progress ]; then bar=--progress-bar; else bar=-sS; fi
  curl --fail --location --proto-redir =https --retry 3 --retry-delay 2 --connect-timeout 15 $bar -o "$2" "$1" ||
    die "Could not download $1 (curl says why above). Nothing was installed."
}

quit_app() { # path to an installed Bellpip.app
  # the login item restarts Bellpip after a crash, and a pkill below counts as one: stop the job first (it comes back at
  # the next login, or when the new app turns launch at login on)
  launchctl bootout "gui/$(id -u)/com.bellpip.app" >/dev/null 2>&1 || true
  pgrep -f "$1/Contents/MacOS/" >/dev/null || return 0
  say "Quitting the running Bellpip"
  osascript -e "with timeout of 5 seconds" -e "tell application \"$1\" to quit" -e "end timeout" >/dev/null 2>&1 || true
  i=0
  while pgrep -f "$1/Contents/MacOS/" >/dev/null && [ $i -lt 10 ]; do sleep 0.5; i=$((i + 1)); done
  if pgrep -f "$1/Contents/MacOS/" >/dev/null; then
    pkill -f "$1/Contents/MacOS/" || true
    sleep 1
  fi
}

# every VS Code-family editor installed (VS Code, Cursor and the forks: Windsurf, VSCodium, Antigravity, Kiro, Trae...),
# one CLI path per line: they all carry VS Code's product.json, which names the CLI in the app's bin folder
editor_clis() {
  for a in /Applications/*.app "$HOME"/Applications/*.app; do
    p="$a/Contents/Resources/app/product.json"
    [ -f "$p" ] || continue
    n=$(plutil -extract applicationName raw -o - "$p" 2>/dev/null) || continue
    b="$a/Contents/Resources/app/bin"
    if [ -x "$b/$n" ]; then echo "$b/$n"; elif [ -x "$b/code" ]; then echo "$b/code"; fi  # Insiders: code-insiders ships as bin/code
  done
  return 0
}

# The Bellpip Focus extension lets a click on a session jump to its terminal tab in VS Code, Cursor and their forks. It
# is not on any Marketplace, so each editor's own CLI installs the .vsix inside the app. Best effort: it never stops the install.
install_editor_extension() { # path to the installed Bellpip.app
  vsix="$1/Contents/Resources/bellpip-focus.vsix"
  [ -f "$vsix" ] || return 0
  editor_clis | while IFS= read -r cli; do
    name=$(basename "${cli%/Contents/Resources/app/bin/*}" .app)
    say "Adding the Bellpip Focus extension to $name"
    # The editor asks "Allow 'Bellpip Focus' extension to open this URI?" on the first jump (it does for any extension
    # not from its Marketplace); that choice is the user's, so we only say what to click.
    # shellcheck disable=SC2086  # BELLPIP_EDITOR_ARGS is meant to split into words
    if "$cli" ${BELLPIP_EDITOR_ARGS:-} --install-extension "$vsix" --force >/dev/null 2>&1; then
      echo "    The first time you click a session, $name asks to allow it: tick \"Do not ask me again\" and click Open."
    else
      echo "    Could not add it to $name. Later: $name > Extensions > ... > Install from VSIX, and pick $vsix"
    fi
  done
}

main() {
  check_mac
  url=${BELLPIP_URL:-https://bellpip.com/download/Bellpip-latest.zip}

  tmp=$(mktemp -d "${TMPDIR:-/tmp}/bellpip-install.XXXXXX")
  trap 'rm -rf "$tmp"' EXIT
  trap 'exit 130' INT
  trap 'exit 143' TERM

  say "Downloading Bellpip"
  download "$url" "$tmp/Bellpip.zip" progress
  download "$url.sha256" "$tmp/Bellpip.zip.sha256"

  say "Checking the download"
  want=$(awk 'NR == 1 { print tolower($1) }' "$tmp/Bellpip.zip.sha256")
  case "$want" in
    *[!0-9a-f]* | "") die "The checksum file is not a SHA-256 hash. Nothing was installed." ;;
  esac
  [ ${#want} -eq 64 ] || die "The checksum file is not a SHA-256 hash. Nothing was installed."
  got=$(shasum -a 256 "$tmp/Bellpip.zip" | awk '{ print tolower($1) }')
  [ "$got" = "$want" ] || die "The download is damaged or was changed (SHA-256 mismatch). Nothing was installed."

  ditto -x -k "$tmp/Bellpip.zip" "$tmp/unzipped" || die "Could not unpack the download. Nothing was installed."
  new="$tmp/unzipped/Bellpip.app"
  [ -d "$new" ] || die "The download has no Bellpip.app inside. Nothing was installed."
  # --deep: without it the helpers inside (bellpip-hook, bellpip-duck, the link app) are not checked, only listed
  codesign --verify --deep --strict "$new" 2>/dev/null || die "Bellpip.app's signature is broken. Nothing was installed."

  if [ -n "${BELLPIP_DEST:-}" ]; then dest=$BELLPIP_DEST
  elif [ -w /Applications ]; then dest=/Applications
  else dest="$HOME/Applications"
  fi
  mkdir -p "$dest" || die "Could not create $dest."
  app="$dest/Bellpip.app"

  # Copy in under a hidden name first: the same disk as the target, so the swap below is two quick renames.
  say "Installing to $dest"
  staged="$dest/.Bellpip.app.new.$$"
  old="$dest/.Bellpip.app.old.$$"
  trap 'rm -rf "$tmp" "$staged"' EXIT
  ditto "$new" "$staged" || die "Could not copy Bellpip.app into $dest."

  quit_app "$app"
  if [ -e "$app" ]; then
    mv "$app" "$old" || die "Could not move the old Bellpip.app aside. Is it open in another account?"
  fi
  if ! mv "$staged" "$app"; then
    [ -e "$old" ] && mv "$old" "$app"
    die "Could not put Bellpip.app in $dest. The old copy was kept."
  fi
  rm -rf "$old"

  # curl does not quarantine what it downloads, so this is a no-op unless something else added it.
  xattr -dr com.apple.quarantine "$app" 2>/dev/null || true
  codesign --verify --deep --strict "$app" 2>/dev/null || die "The installed Bellpip.app fails its signature check: $app"

  install_editor_extension "$app"

  say "Opening Bellpip"
  open "$app" --args --welcome || die "Installed, but could not open it. Open $app yourself."
  say "Done. Bellpip is in $dest and will walk you through the rest."
}

main "$@"
