#!/bin/bash
# AntipodesPrint for macOS: install or update with one command, without the
# "Apple could not verify … Not Opened" dialog.
#
#   curl -fsSL https://files.prim.bg/Desktop/beta/macOS/install.sh | bash
#
# The app is not signed with an Apple Developer ID, and macOS refuses such an app
# when it was downloaded by a browser: the browser marks the file as "from the
# internet" (com.apple.quarantine). curl does not, so the same .dmg fetched here
# opens normally. Run it again to update to the latest version.
#
# Overrides, for testing: INSTALL_DIR (default /Applications, or ~/Applications
# when /Applications is not writable), NO_OPEN=1 to not start the app.
set -euo pipefail

BASE=https://files.prim.bg/Desktop/beta
APP=AntipodesPrint.app

dest=${INSTALL_DIR:-/Applications}
if [ ! -w "$dest" ]; then
  dest="$HOME/Applications"
  mkdir -p "$dest"
fi

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

curl -fsSL "$BASE/latest.json" -o "$tmp/latest.json"
field() { plutil -extract "platforms.macos.$1" raw -o - "$tmp/latest.json"; }
url=$(field url)
md5=$(field md5)
build=$(field build)

echo "AntipodesPrint v$build: downloading…"
curl -fL --progress-bar "$BASE/$url" -o "$tmp/app.dmg"
if [ "$(md5 -q "$tmp/app.dmg")" != "$md5" ]; then
  echo "The download is damaged (md5 does not match). Nothing was installed; try again." >&2
  exit 1
fi

hdiutil attach -quiet -nobrowse -readonly -mountpoint "$tmp/mnt" "$tmp/app.dmg"

# A running copy would keep the old files in use.
pkill -x printer_flut_app 2>/dev/null && sleep 1 || true

rm -rf "${dest:?}/$APP"
ditto "$tmp/mnt/$APP" "$dest/$APP"
# In case an older copy came from a browser download.
xattr -dr com.apple.quarantine "$dest/$APP" 2>/dev/null || true
# Make Finder and the Dock read this bundle's icon, not one cached for the app's
# bundle id (Flutter's default, on Macs that had the very first build).
touch "$dest/$APP"
/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -f "$dest/$APP" 2>/dev/null || true

echo "AntipodesPrint v$build is installed in $dest."
if [ -z "${NO_OPEN:-}" ]; then
  open "$dest/$APP"
fi
