#!/bin/bash
# Installs Earshot on this Mac:
#   curl -fsSL https://earshot-umber.vercel.app/install.sh | bash
#
# It downloads the same disk image as the website's download button, copies Earshot into
# Applications, and opens it. Nothing else is touched.
set -euo pipefail

SITE="https://earshot-umber.vercel.app"
say() { printf '\033[1m%s\033[0m\n' "$*"; }
fail() { printf 'Earshot: %s\n' "$*" >&2; exit 1; }

[ "$(uname -s)" = "Darwin" ] || fail "Earshot is a Mac app."
[ "$(uname -m)" = "arm64" ] || fail "Earshot needs a Mac with Apple silicon."
major=$(sw_vers -productVersion | cut -d. -f1)
[ "$major" -ge 15 ] || fail "Earshot needs macOS 15 or later. This Mac has $(sw_vers -productVersion)."

work=$(mktemp -d)
mnt="$work/mnt"
cleanup() { hdiutil detach "$mnt" -quiet 2>/dev/null || true; rm -f "$work/Earshot.dmg"; rmdir "$mnt" "$work" 2>/dev/null || true; }
trap cleanup EXIT

say "Downloading Earshot…"
curl -fL --progress-bar "$SITE/download/Earshot.dmg" -o "$work/Earshot.dmg"

mkdir "$mnt"
hdiutil attach "$work/Earshot.dmg" -nobrowse -readonly -mountpoint "$mnt" -quiet
[ -d "$mnt/Earshot.app" ] || fail "The download didn't contain Earshot.app. Please try again."
codesign --verify --strict "$mnt/Earshot.app" || fail "The download's signature didn't check out. Please try again."

# Update in place if it's already installed; otherwise Applications, or ~/Applications without admin rights.
if [ -d "$HOME/Applications/Earshot.app" ] && [ ! -d "/Applications/Earshot.app" ]; then
  dest="$HOME/Applications"
else
  dest="/Applications"
  [ -w "$dest" ] || { dest="$HOME/Applications"; mkdir -p "$dest"; }
fi

if pgrep -x Earshot >/dev/null; then
  say "Closing the running copy…"
  pkill -x Earshot || true
  sleep 1
fi

say "Installing into $dest…"
rm -rf "$dest/Earshot.app.new"
ditto "$mnt/Earshot.app" "$dest/Earshot.app.new"
rm -rf "$dest/Earshot.app"
mv "$dest/Earshot.app.new" "$dest/Earshot.app"

open "$dest/Earshot.app"
say "Earshot is installed. Select some text and press Option-Shift-Space."
