#!/usr/bin/env bash
# Installs or updates Sonar on macOS:
#   curl -fsSL https://sonar.parieaw.cloud/install.sh | bash
#   curl -fsSL https://sonar.parieaw.cloud/install.sh | SONAR_FORCE=1 bash   # reinstall the same version
#
# What it does: asks the site for the latest release, downloads Sonar.app as a .tar.gz,
# checks its sha512 against the release manifest, and puts it in /Applications
# (or ~/Applications if that isn't writable). Files fetched by curl don't get
# macOS's quarantine flag, so there's no "unidentified developer" prompt.
set -euo pipefail

BASE="${SONAR_BASE:-https://sonar.parieaw.cloud}"
DEST="${SONAR_INSTALL_DIR:-/Applications}"

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

[ "$(uname -s)" = "Darwin" ] || die "Sonar is a macOS app."
[ "$(uname -m)" = "arm64" ] || die "This build is for Apple Silicon Macs (M1 or newer). Intel isn't supported yet."

say "Checking the latest release…"
json="$(curl -fsSL "${BASE}/api/latest")" || die "Couldn't reach ${BASE}."
field() { plutil -extract "$1" raw -o - - <<<"${json}" 2>/dev/null || die "The release manifest is missing $1."; }
version="$(field version)"
name="$(field files.app.name)"
sha="$(field files.app.sha512)"

current=""
if [ -d "${DEST}/Sonar.app" ]; then
  current="$(defaults read "${DEST}/Sonar.app/Contents/Info" CFBundleShortVersionString 2>/dev/null || true)"
fi
if [ "${current}" = "${version}" ] && [ -z "${SONAR_FORCE:-}" ]; then
  say "Sonar ${version} is already installed in ${DEST}. To reinstall it, run again with SONAR_FORCE=1."
  exit 0
fi

tmp="$(mktemp -d)"
trap 'rm -rf "${tmp}"' EXIT

say "Downloading Sonar ${version}…"
curl -fL --progress-bar "${BASE}/download/${version}/${name}" -o "${tmp}/${name}" || die "Download failed."

say "Checking sha512…"
got="$(shasum -a 512 "${tmp}/${name}" | awk '{print $1}')"
[ "${got}" = "${sha}" ] || die "Checksum doesn't match the release. Nothing was installed."

tar -xzf "${tmp}/${name}" -C "${tmp}"
[ -d "${tmp}/Sonar.app" ] || die "The download didn't contain Sonar.app."

if pgrep -f "Sonar.app/Contents/MacOS/" >/dev/null 2>&1; then
  say "Closing the running Sonar…"
  osascript -e 'quit app "Sonar"' >/dev/null 2>&1 || true
  sleep 1
fi

if ! [ -w "${DEST}" ]; then
  DEST="${HOME}/Applications"
  mkdir -p "${DEST}"
fi
rm -rf "${DEST}/Sonar.app"
mv "${tmp}/Sonar.app" "${DEST}/"
xattr -dr com.apple.quarantine "${DEST}/Sonar.app" 2>/dev/null || true

if [ -n "${current}" ]; then
  say "Updated Sonar ${current} → ${version} in ${DEST}."
else
  say "Installed Sonar ${version} in ${DEST}."
fi
say "Open it with: open -a Sonar"
