#!/bin/bash
# Generated from scripts/macos/install-mac.sh by publish-install-script.sh — do not edit.
# Install or update NeuroSwitcher on a Mac with one command:
#
#   curl -fsSL https://neuroswitcher.app/install-mac.sh | bash
#
# Why a script at all: until the app is notarised, a DMG downloaded in a
# browser is quarantined and macOS stops its first launch ("Open Anyway" in
# System Settings). A file fetched by curl carries no quarantine flag, so this
# path never shows that dialog. In exchange the script checks what Gatekeeper
# would otherwise vouch for: the published sha256 and OUR signing certificate.
#
# What it does: checks the Mac (Apple Silicon, macOS 13+), downloads the DMG
# named by the site's manifest, verifies sha256 + signature, quits a running
# NeuroSwitcher, replaces /Applications/NeuroSwitcher.app and starts it.
# Settings, dictionary, license and recordings live in
# ~/Library/Application Support/NeuroSwitcher and are not touched.
#
# NS_SITE=<url>  install from another site. landing/ and landing-ru/ carry
#                generated copies: scripts/macos/publish-install-script.sh
# NS_DMG=<path>  install a local DMG instead of downloading (testing a build)

set -euo pipefail

SITE="${NS_SITE:-https://neuroswitcher.app}"
APP="/Applications/NeuroSwitcher.app"
UA="NeuroSwitcher-Installer/1 (macos)"
# Leaf certificate the release is signed with ("NeuroSwitcher Local Signing").
# Changes once, when the build moves to an Apple Developer ID.
CERT_LEAF="f5b97d6daa1e4ec468248f8325b92386f460aedc"

say()  { printf '\033[1m==>\033[0m %s\n' "$*"; }
die()  { printf '\033[31m!!\033[0m %s\n' "$*" >&2; exit 1; }

[[ "$(uname -s)" == "Darwin" ]] || die "This installer is for macOS."
[[ "$(uname -m)" == "arm64" ]] || die "NeuroSwitcher for Mac needs Apple Silicon (M1 or newer). Intel Macs are not supported yet."
major="$(sw_vers -productVersion | cut -d. -f1)"
(( major >= 13 )) || die "NeuroSwitcher needs macOS 13 Ventura or newer (this Mac has $(sw_vers -productVersion))."

WORK="$(mktemp -d)"
MNT="$WORK/mnt"
cleanup() {
  hdiutil detach -quiet "$MNT" 2>/dev/null || true
  rm -rf "$WORK"
}
trap cleanup EXIT

if [[ -n "${NS_DMG:-}" ]]; then
  DMG="$NS_DMG"
  [[ -f "$DMG" ]] || die "No such file: $DMG"
  say "Installing from $DMG"
else
  say "Checking the latest version on ${SITE#https://}"
  manifest="$(curl -fsSL -A "$UA" "$SITE/v1/latest?platform=macos")" \
    || die "Could not reach $SITE. Check the connection and try again."
  field() { plutil -extract "$1" raw -o - - <<<"$manifest" 2>/dev/null; }
  version="$(field version)"; file="$(field filename)"; sha="$(field sha256)"
  [[ -n "$file" && -n "$sha" && "$file" != */* ]] || die "The site returned an unexpected answer."
  if [[ -d "$APP" ]]; then
    have="$(/usr/libexec/PlistBuddy -c 'Print CFBundleShortVersionString' "$APP/Contents/Info.plist" 2>/dev/null || echo '?')"
    say "Installed: $have, available: $version"
  fi
  DMG="$WORK/$file"
  say "Downloading $file"
  curl -fL --progress-bar -A "$UA" -o "$DMG" "$SITE/download/$file" || die "Download failed."
  got="$(shasum -a 256 "$DMG" | awk '{print $1}')"
  [[ "$got" == "$sha" ]] || die "Checksum mismatch — the download is damaged. Nothing was changed."
fi

say "Checking the signature"
mkdir -p "$MNT"
hdiutil attach -quiet -nobrowse -readonly -mountpoint "$MNT" "$DMG" || die "Could not open the disk image."
NEW="$MNT/NeuroSwitcher.app"
[[ -d "$NEW" ]] || die "The disk image does not contain NeuroSwitcher.app."
codesign --verify --deep --strict "$NEW" 2>/dev/null || die "The app's signature is broken. Nothing was changed."
codesign -dr - "$NEW" 2>&1 | grep -qi "$CERT_LEAF" \
  || die "The app is not signed by NeuroSwitcher. Nothing was changed."

if pgrep -x ks-app >/dev/null || pgrep -x ks-pro-ui >/dev/null; then
  say "Closing the running NeuroSwitcher"
  for p in ks-pro-ui ks-meeting-host ks-voice-host ks-app; do pkill -x "$p" 2>/dev/null || true; done
  for _ in 1 2 3 4 5 6 7 8 9 10; do pgrep -x ks-app >/dev/null || break; sleep 0.5; done
  pgrep -x ks-app >/dev/null && pkill -9 -x ks-app 2>/dev/null || true
fi

say "Installing to $APP"
SUDO=""
if [[ -e "$APP" && ! -w "$APP" ]] || [[ ! -w /Applications ]]; then
  say "Your password is needed to write to Applications."
  SUDO="sudo"
fi
# Copy beside, then swap: a failed copy leaves the old app working.
$SUDO rm -rf "$APP.new"
$SUDO ditto "$NEW" "$APP.new"
$SUDO rm -rf "$APP"
$SUDO mv "$APP.new" "$APP"
$SUDO xattr -dr com.apple.quarantine "$APP" 2>/dev/null || true

v="$(/usr/libexec/PlistBuddy -c 'Print CFBundleShortVersionString' "$APP/Contents/Info.plist")"
say "NeuroSwitcher $v installed. Starting it."
open "$APP"
echo
echo "If this is the first install: allow NeuroSwitcher in"
echo "System Settings → Privacy & Security → Accessibility, then restart it."
echo "Updates keep that permission."
