#!/bin/sh
# Brim installer.  Usage:  curl -fsSL https://brim-ehw.pages.dev/install.sh | sh
#
# What it does, in order:
#   1. Reads https://brim-ehw.pages.dev/latest.json (version, download URL, SHA-256, minimum macOS).
#   2. Downloads the zip with curl and checks its SHA-256. curl does not set the quarantine flag,
#      so macOS opens the app without the "can't verify" dialog.
#   3. Checks the app's code signature (signed with Brim's own certificate, not notarized by Apple).
#   4. Installs Brim.app into /Applications, asking first if a Brim is already there (quits it nicely).
#   5. Optionally links the `brim` command into ~/.local/bin.
#   6. Opens Brim.
# It never uses sudo unless /Applications is not writable, and then it says so and asks.
# Environment: BRIM_SITE (default https://brim-ehw.pages.dev), BRIM_YES=1 (answer yes to every question).
set -eu

SITE=${BRIM_SITE:-https://brim-ehw.pages.dev}
DEST=/Applications/Brim.app
BIN_DIR="$HOME/.local/bin"

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

# Questions read from the terminal, since stdin is this script when piped from curl.
ask() {
    if [ "${BRIM_YES:-}" = 1 ]; then return 0; fi
    if ! [ -r /dev/tty ]; then return 1; fi
    printf '%s [y/N] ' "$1" > /dev/tty
    read -r answer < /dev/tty || return 1
    case $answer in [yY]*) return 0 ;; *) return 1 ;; esac
}

# The value of a string field in latest.json (flat, known format; no jq on a stock Mac).
field() { # field <json> <object-or-empty> <key>
    if [ -n "$2" ]; then
        printf '%s' "$1" | tr -d '\n' | sed -n "s/.*\"$2\" *: *{[^}]*\"$3\" *: *\"\([^\"]*\)\".*/\1/p"
    else
        printf '%s' "$1" | tr -d '\n' | sed -n "s/.*\"$3\" *: *\"\([^\"]*\)\".*/\1/p"
    fi
}

version_ge() { # version_ge 15.4 15.0  -> true when $1 >= $2
    [ "$(printf '%s\n%s\n' "$2" "$1" | sort -t. -k1,1n -k2,2n -k3,3n | head -n1)" = "$2" ]
}

[ "$(uname -s)" = Darwin ] || die "Brim is a macOS app."
[ "$(uname -m)" = arm64 ] || die "Brim needs an Apple Silicon Mac (M1 or newer)."

say "Checking the latest Brim at $SITE ..."
LATEST=$(curl -fsSL "$SITE/latest.json") || die "Could not reach $SITE/latest.json"
VERSION=$(field "$LATEST" "" version)
MIN_OS=$(field "$LATEST" "" minimum_macos)
SHA=$(field "$LATEST" zip sha256)
[ -n "$VERSION" ] && [ -n "$SHA" ] || die "latest.json is not in the expected format."

OS=$(sw_vers -productVersion)
version_ge "$OS" "${MIN_OS:-15.0}" || die "Brim $VERSION needs macOS $MIN_OS or later; this Mac has $OS."

TMP=$(mktemp -d "${TMPDIR:-/tmp}/brim-install.XXXXXX")
trap 'rm -rf "$TMP"' EXIT

say "Downloading Brim $VERSION ..."
curl -fL --progress-bar -o "$TMP/Brim.zip" "$SITE/download/zip?via=script" || die "Download failed."
GOT=$(shasum -a 256 "$TMP/Brim.zip" | cut -d' ' -f1)
[ "$GOT" = "$SHA" ] || die "Checksum mismatch (expected $SHA, got $GOT). Nothing was installed."
say "Checksum OK."

ditto -x -k "$TMP/Brim.zip" "$TMP/out"
[ -d "$TMP/out/Brim.app" ] || die "The download does not contain Brim.app."
codesign --verify --deep --strict "$TMP/out/Brim.app" 2>/dev/null || die "Brim.app's code signature is broken. Nothing was installed."

SUDO=""
if ! [ -w /Applications ]; then
    say "/Applications is not writable by your user, so copying Brim there needs your admin password (sudo)."
    ask "Use sudo for the copy?" || die "Stopped. You can drag Brim.app from $TMP/out yourself."
    SUDO=sudo
fi

if [ -d "$DEST" ]; then
    OLD=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$DEST/Contents/Info.plist" 2>/dev/null || echo unknown)
    ask "Replace Brim $OLD in /Applications with $VERSION?" || die "Stopped. Your current Brim is untouched."
    if pgrep -xq Brim; then
        say "Quitting Brim ..."
        osascript -e 'tell application id "dev.daniel.brim" to quit' >/dev/null 2>&1 || true
        i=0
        while pgrep -xq Brim && [ $i -lt 20 ]; do sleep 0.5; i=$((i + 1)); done
        pgrep -xq Brim && die "Brim is still running. Quit it from its menu bar icon and run this again."
    fi
    $SUDO rm -rf "$DEST"
fi

$SUDO ditto "$TMP/out/Brim.app" "$DEST"
say "Installed Brim $VERSION in /Applications."

if ask "Link the brim command into $BIN_DIR (for Claude Code hooks and scripts)?"; then
    mkdir -p "$BIN_DIR"
    ln -sf "$DEST/Contents/Helpers/brim" "$BIN_DIR/brim"
    say "Linked $BIN_DIR/brim."
    case ":$PATH:" in *":$BIN_DIR:"*) ;; *) say "Note: $BIN_DIR is not on your PATH. Add it in your shell profile." ;; esac
fi

open "$DEST"
say "Brim is running: look at your notch. Brim sends one anonymous ping a day; turn it off in Settings."
