#!/bin/bash
# Aether Desktop installer for macOS.
#
#   curl -fsSL https://www.aether-automation.xyz/install.sh | bash
#
# Downloads the latest release, copies Aether Desktop into /Applications and
# opens it. Because the file comes in through curl and not through a browser,
# macOS does not attach its "downloaded from the internet" flag, so there is
# no "could not verify" dialog on first launch.
set -euo pipefail

say() { printf '\033[1;35m▸\033[0m %s\n' "$*"; }
fail() { printf '\033[1;31m✕\033[0m %s\n' "$*" >&2; exit 1; }

[ "$(uname -s)" = Darwin ] || fail "This installer is for macOS. On Windows, use install.ps1."
[ "$(uname -m)" = arm64 ] || fail "Aether needs a Mac with Apple Silicon (M1 or newer)."
MAJOR="$(sw_vers -productVersion | cut -d. -f1)"
[ "$MAJOR" -ge 15 ] || fail "Aether needs macOS 15 Sequoia or later (you have $(sw_vers -productVersion))."

say "Looking up the latest version"
MANIFEST="$(curl -fsSL https://www.aether-automation.xyz/desktop/update.json)"
DMG_URL="$(printf '%s' "$MANIFEST" | sed -n 's/.*"dmg": *"\([^"]*\)".*/\1/p' | head -1)"
VERSION="$(printf '%s' "$MANIFEST" | sed -n 's/.*"version": *"\([^"]*\)".*/\1/p' | head -1)"
case "$DMG_URL" in https://github.com/aethercaptions/*) ;; *) fail "Unexpected download address. Please use the website instead." ;; esac

TMP="$(mktemp -d)"
MNT="$TMP/mnt"
trap 'hdiutil detach -quiet "$MNT" 2>/dev/null || true; rm -rf "$TMP"' EXIT

say "Downloading Aether Desktop $VERSION (about 400 MB)"
curl -fL --progress-bar "$DMG_URL" -o "$TMP/Aether.dmg"

say "Installing into /Applications"
mkdir -p "$MNT"
hdiutil attach -quiet -nobrowse -readonly -mountpoint "$MNT" "$TMP/Aether.dmg"
osascript -e 'tell application id "xyz.aether-automation.desktop" to quit' >/dev/null 2>&1 || true
sleep 1
if [ -w /Applications ]; then
  rm -rf "/Applications/Aether Desktop.app"
  ditto "$MNT/Aether Desktop.app" "/Applications/Aether Desktop.app"
else
  say "Your password is needed to write to /Applications"
  sudo rm -rf "/Applications/Aether Desktop.app"
  sudo ditto "$MNT/Aether Desktop.app" "/Applications/Aether Desktop.app"
fi

say "Done. Opening Aether"
open "/Applications/Aether Desktop.app"
