#!/bin/bash
set -euo pipefail

cd "$(dirname "$0")"
SOURCE_APP="$PWD/MacExplorer.app"
INSTALLED_APP="/Applications/MacExplorer.app"

if [ ! -d "$SOURCE_APP" ]; then
  echo "MacExplorer.app must be beside this installer."
  read -r -p "Press Return to close."
  exit 1
fi

echo "Replacing the previously installed Mac Explorer…"
osascript -e 'tell application "MacExplorer" to quit' 2>/dev/null || true
pkill -f "/Applications/MacExplorer.app" 2>/dev/null || true
rm -rf "$INSTALLED_APP"
ditto "$SOURCE_APP" "$INSTALLED_APP"
xattr -cr "$INSTALLED_APP"

# Do not re-sign this app locally. On macOS 26, applying hardened-runtime
# ad-hoc signatures to Electron's V8 helpers causes a launch-time SIGTRAP on
# ThreadPoolForegroundWorker. The packaged bundle already contains Electron's
# compatible signatures; preserve them exactly and only clear quarantine.
if ! codesign --verify --deep --verbose=2 "$INSTALLED_APP"; then
  echo "The app archive is damaged or was modified after extraction."
  echo "Download a fresh copy of MacExplorer-macOS-arm64-v6.zip and try again."
  read -r -p "Press Return to close."
  exit 1
fi

echo "Installation verified. Opening /Applications/MacExplorer.app…"
open "$INSTALLED_APP"
