#!/bin/sh
# Brocoded installer for macOS:  curl -fsSL https://brocoded.cloud/install.sh | sh
#
# What it does (read it, it is short): downloads the Mac app for your chip from the same place the website's download button uses,
# copies Brocoded.app to /Applications and opens it. A file fetched by curl is not tagged "downloaded from the internet", so macOS
# does not show the "can't verify" warning. Your pairing and account (in ~/.foreman) are kept. Nothing else is touched.
#
# Test without installing:  curl -fsSL https://brocoded.cloud/install.sh | BROCODED_DRY=1 sh
set -eu

SITE="${BROCODED_SITE:-https://brocoded.cloud}"
[ "$(uname -s)" = "Darwin" ] || { echo "This installer is for macOS. Windows: download the installer at ${SITE}/downloads/"; exit 1; }
case "$(uname -m)" in arm64) KIND="mac-arm64" ;; *) KIND="mac-x64" ;; esac

TMP="$(mktemp -d)"
MNT="$TMP/volume"
cleanup() { hdiutil detach -quiet "$MNT" 2>/dev/null || true; rm -rf "$TMP"; }
trap cleanup EXIT INT TERM

echo "Finding the latest Brocoded for your Mac (${KIND})…"
curl -fsSL "${SITE}/releases.json" -o "$TMP/releases.json"
URL="$(/usr/bin/plutil -extract "${KIND}.url" raw -o - "$TMP/releases.json")"
VERSION="$(/usr/bin/plutil -extract "${KIND}.version" raw -o - "$TMP/releases.json")"
SIZE="$(/usr/bin/plutil -extract "${KIND}.size" raw -o - "$TMP/releases.json")"
SHA="$(/usr/bin/plutil -extract "${KIND}.sha256" raw -o - "$TMP/releases.json" 2>/dev/null || true)"

echo "Downloading Brocoded ${VERSION}…"
curl -fL --progress-bar "$URL" -o "$TMP/Brocoded.dmg"
GOT="$(stat -f%z "$TMP/Brocoded.dmg")"
[ "$GOT" = "$SIZE" ] || { echo "The download is incomplete ($GOT of $SIZE bytes). Please try again."; exit 1; }
if [ -n "$SHA" ]; then
  HAVE="$(shasum -a 256 "$TMP/Brocoded.dmg" | cut -d' ' -f1)"
  [ "$HAVE" = "$SHA" ] || { echo "The download doesn't match its checksum. Nothing was installed. Please try again."; exit 1; }
fi

hdiutil attach -nobrowse -quiet -mountpoint "$MNT" "$TMP/Brocoded.dmg"
[ -d "$MNT/Brocoded.app" ] || { echo "The download doesn't contain Brocoded.app."; exit 1; }

if [ "${BROCODED_DRY:-}" = "1" ]; then
  echo "Dry run: downloaded and checked Brocoded ${VERSION} (${KIND}). Nothing was installed."
  exit 0
fi

if pgrep -qf "Brocoded.app/Contents"; then
  echo "Closing the running Brocoded (sessions running under it stop and come back when it reopens)…"
  osascript -e 'tell application "Brocoded" to quit' >/dev/null 2>&1 || true
  sleep 3
  pkill -f "Brocoded.app/Contents" >/dev/null 2>&1 || true
fi

DEST="/Applications"
[ -w "${DEST}" ] || { DEST="$HOME/Applications"; mkdir -p "${DEST}"; }
rm -rf "${DEST}/Brocoded.app"
cp -R "$MNT/Brocoded.app" "${DEST}/Brocoded.app"
xattr -dr com.apple.quarantine "${DEST}/Brocoded.app" 2>/dev/null || true

echo "Installed Brocoded ${VERSION} in ${DEST}. Opening it…"
open "${DEST}/Brocoded.app"
