#!/bin/sh
set -eu

if [ "$(uname -s)" != "Darwin" ]; then
  echo "Nico Desktop currently supports macOS." >&2
  exit 1
fi

DOWNLOAD_URL="https://nico.macrodeep.com/updates/mac/Nico.dmg"
INSTALL_DIR="${NICO_INSTALL_DIR:-/Applications}"
TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/nico-install.XXXXXX")"
MOUNT_POINT=""

cleanup() {
  if [ -n "$MOUNT_POINT" ]; then
    hdiutil detach "$MOUNT_POINT" >/dev/null 2>&1 || true
  fi
  rm -rf "$TMP_DIR"
}
trap cleanup EXIT HUP INT TERM

echo "Downloading Nico…"
curl -fL --progress-bar "$DOWNLOAD_URL" -o "$TMP_DIR/Nico.dmg"

echo "Opening installer image…"
MOUNT_POINT="$(hdiutil attach -nobrowse -readonly "$TMP_DIR/Nico.dmg" | sed -n 's#^.*\(/Volumes/.*\)$#\1#p' | tail -n 1)"
APP_PATH="$(find "$MOUNT_POINT" -maxdepth 2 -name 'Nico.app' -type d -print -quit)"

if [ -z "$APP_PATH" ]; then
  echo "Nico.app was not found in the downloaded image." >&2
  exit 1
fi

echo "Installing Nico in $INSTALL_DIR…"
if [ -w "$INSTALL_DIR" ]; then
  ditto "$APP_PATH" "$INSTALL_DIR/Nico.app"
else
  sudo ditto "$APP_PATH" "$INSTALL_DIR/Nico.app"
fi

echo "Nico is installed. Open it from Applications."
