#!/bin/sh
set -eu

BASE_URL="https://get.melonite.ai"
APP_DIR="${MELONITE_APP_DIR:-/Applications}"

err() { echo "install: $*" >&2; exit 1; }
info() { echo "melonite› $*"; }

os="$(uname -s)"
[ "$os" = "Darwin" ] || err "the Melonite desktop app is macOS-only (got '$os'). See https://github.com/meloniteai/melonite-desktop/releases/latest"

if command -v curl >/dev/null 2>&1; then
  fetch() { curl -fsSL "$1"; }
  download() { curl -fsSL "$1" -o "$2"; }
elif command -v wget >/dev/null 2>&1; then
  fetch() { wget -qO- "$1"; }
  download() { wget -qO "$2" "$1"; }
else
  err "need curl or wget installed"
fi

info "looking up the latest release..."
version="$(fetch "$BASE_URL/desktop/latest")" \
  || err "could not query the latest Melonite release"
printf '%s\n' "$version" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$' \
  || err "invalid latest release version '$version'"

asset_url="$BASE_URL/desktop/releases/$version/Melonite_aarch64.dmg"
tmp="$(mktemp -d)"
mnt="$tmp/mnt"
dmg="$tmp/melonite.dmg"
cleanup() {
  if [ -d "$mnt" ]; then hdiutil detach "$mnt" -quiet >/dev/null 2>&1 || true; fi
  rm -rf "$tmp"
}
trap cleanup EXIT

info "downloading Melonite $version..."
download "$asset_url" "$dmg" || err "could not download Melonite $version"

mkdir -p "$mnt"
hdiutil attach "$dmg" -nobrowse -quiet -mountpoint "$mnt" \
  || err "could not mount the downloaded disk image"

app_src="$(/bin/ls -d "$mnt"/*.app 2>/dev/null | head -n1)"
[ -n "$app_src" ] || err "disk image did not contain a .app bundle"
app_name="$(basename "$app_src")"
dest="$APP_DIR/$app_name"

need_sudo=""
if [ ! -w "$APP_DIR" ]; then
  command -v sudo >/dev/null 2>&1 || err "$APP_DIR is not writable and sudo is unavailable; set MELONITE_APP_DIR to a writable directory"
  need_sudo=1
  info "$APP_DIR needs elevated permissions; you may be prompted for your password"
fi
run() { if [ -n "$need_sudo" ]; then sudo "$@"; else "$@"; fi; }

info "installing $app_name to $APP_DIR..."
run rm -rf "$dest"
run /usr/bin/ditto "$app_src" "$dest" || err "could not copy $app_name into $APP_DIR"

run /usr/bin/xattr -dr com.apple.quarantine "$dest" >/dev/null 2>&1 \
  || err "could not remove the quarantine attribute from $dest"
if run /usr/bin/xattr -r -l "$dest" 2>/dev/null | grep -q 'com\.apple\.quarantine'; then
  err "the quarantine attribute is still present on $dest"
fi

installed_version="$(/usr/bin/defaults read "$dest/Contents/Info.plist" CFBundleShortVersionString 2>/dev/null || true)"
if [ -n "$installed_version" ]; then
  info "installed $app_name $installed_version to $dest"
else
  info "installed $app_name to $dest"
fi
info "launch it with: open -a \"$app_name\""
info "done."
