#!/bin/sh
# Makoda installer for Apple silicon Macs.
#   curl -fsSL https://makoda.ai/install.sh | sh
#
# Reads the signed update manifest, downloads that exact app archive, checks its SHA-256
# against the published SHA256SUMS, then installs Makoda.app into /Applications (or
# ~/Applications when /Applications is not writable) and opens it. No sudo, nothing else
# is installed. Environment overrides for testing: MAKODA_INSTALL_DIR, MAKODA_NO_OPEN=1.
set -eu

BASE="https://releases.makoda.ai"
# Earlier manifests point at the bucket's r2.dev address; both serve the same bucket.
LEGACY_BASE="https://pub-120db31ef46544fea7b1d1e8f2f025d0.r2.dev"
APP="Makoda.app"

say() { printf '%s\n' "$*"; }
fail() { printf 'makoda: %s\n' "$*" >&2; exit 1; }

[ "$(uname -s)" = "Darwin" ] || fail "Makoda currently supports macOS only."
[ "$(uname -m)" = "arm64" ] || fail "Makoda currently supports Apple silicon Macs (M1 or later) only."

if pgrep -x makoda-desktop >/dev/null 2>&1; then
  fail "Makoda is running. Quit it from the menu bar (Cmd-Q), then run this again."
fi

TMP="$(mktemp -d "${TMPDIR:-/tmp}/makoda-install.XXXXXX")"
trap 'rm -rf "$TMP"' EXIT INT TERM

say "Finding the latest Makoda release..."
curl -fsSL "$BASE/latest.json" -o "$TMP/latest.json" || fail "Could not reach the release server."
VERSION="$(sed -n 's/^[[:space:]]*"version":[[:space:]]*"\([^"]*\)".*/\1/p' "$TMP/latest.json" | head -n 1)"
URL="$(sed -n 's/^[[:space:]]*"url":[[:space:]]*"\([^"]*\)".*/\1/p' "$TMP/latest.json" | head -n 1)"
[ -n "$VERSION" ] && [ -n "$URL" ] || fail "The release manifest could not be read."
case "$URL" in "$BASE"/releases/* | "$LEGACY_BASE"/releases/*) ;; *) fail "Unexpected download location in the manifest." ;; esac
ARCHIVE="$(basename "$URL")"

say "Downloading Makoda $VERSION..."
curl -fSL --progress-bar "$URL" -o "$TMP/$ARCHIVE" || fail "Download failed."
curl -fsSL "$BASE/releases/$VERSION/SHA256SUMS" -o "$TMP/SHA256SUMS" || fail "Could not fetch checksums."
EXPECTED="$(awk -v f="$ARCHIVE" '$2 == f { print $1 }' "$TMP/SHA256SUMS")"
ACTUAL="$(shasum -a 256 "$TMP/$ARCHIVE" | awk '{ print $1 }')"
[ -n "$EXPECTED" ] && [ "$EXPECTED" = "$ACTUAL" ] || fail "Checksum mismatch. Nothing was installed."

mkdir "$TMP/app"
tar -xzf "$TMP/$ARCHIVE" -C "$TMP/app"
[ -d "$TMP/app/$APP" ] || fail "The download did not contain $APP."
codesign --verify --deep --strict "$TMP/app/$APP" 2>/dev/null || fail "The app signature did not verify. Nothing was installed."

DEST="${MAKODA_INSTALL_DIR:-}"
if [ -z "$DEST" ]; then
  if [ -w /Applications ]; then DEST=/Applications; else DEST="$HOME/Applications"; fi
fi
mkdir -p "$DEST"
rm -rf "$DEST/$APP.new"
ditto "$TMP/app/$APP" "$DEST/$APP.new"
rm -rf "$DEST/$APP"
mv "$DEST/$APP.new" "$DEST/$APP"

say "Installed Makoda $VERSION in $DEST."
say "Your settings and integrations are kept. Updates install from inside the app."
if [ "${MAKODA_NO_OPEN:-0}" != "1" ]; then
  open "$DEST/$APP"
fi
