#!/usr/bin/env bash
set -euo pipefail

if [[ "$(uname -s)" != "Darwin" ]]; then
  echo "DMG installation is macOS-only" >&2
  exit 2
fi

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
DMG_PATH="${1:-}"
MOUNT_DIR=""

if [[ -z "$DMG_PATH" ]]; then
  DMG_PATH="$(find "$ROOT_DIR/desktop/src-tauri/target" -name "*.dmg" -type f -print 2>/dev/null | sort | tail -n 1)"
fi

if [[ -z "$DMG_PATH" || ! -f "$DMG_PATH" ]]; then
  echo "usage: ./install-dmg.sh [path-to-dmg]" >&2
  exit 2
fi

cleanup() {
  if [[ -n "$MOUNT_DIR" ]]; then
    hdiutil detach "$MOUNT_DIR" -quiet >/dev/null 2>&1 || true
  fi
}
trap cleanup EXIT

MOUNT_DIR="$(mktemp -d "${TMPDIR:-/tmp}/rho-dmg-install.XXXXXX")"
hdiutil attach "$DMG_PATH" -mountpoint "$MOUNT_DIR" -nobrowse -quiet

APP_PATH="$(find "$MOUNT_DIR" -maxdepth 2 -name "*.app" -type d -print | head -n 1)"
if [[ -z "$APP_PATH" ]]; then
  echo "no .app found inside DMG" >&2
  exit 1
fi

DEST="/Applications/$(basename "$APP_PATH")"
rm -rf "$DEST"
cp -R "$APP_PATH" "$DEST"
xattr -rc "$DEST" 2>/dev/null || true
echo "installed $DEST"
