#!/bin/bash
# WordPerfect Preview — installation script.
# Runs as root, called by the AppleScript installer via
# "do shell script ... with administrator privileges".

set -euo pipefail

LSREG=/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister

APP_NAME="WordPerfectPreview.app"
APP_DEST="/Applications/$APP_NAME"
RESOURCES="$(cd "$(dirname "$0")" && pwd)"
ZIP_PATH="$RESOURCES/WordPerfectPreview.zip"

# ── 1. Unregister any old WordPerfect Spotlight importers ─────────────────────
# Find every WordPerfect.mdimporter that is NOT inside our new app and
# unregister its parent app bundle from LaunchServices, so our importer
# wins without competing registrations.

while IFS= read -r imp; do
    parent="$imp"
    while [[ "$parent" != "/" ]]; do
        parent="$(dirname "$parent")"
        if [[ "$parent" == *.app ]]; then
            if [[ "$parent" != "$APP_DEST" ]]; then
                "$LSREG" -u "$parent" 2>/dev/null || true
            fi
            break
        fi
    done
done < <(find /Applications /System/Volumes/Data/Applications \
              "$HOME/Applications" 2>/dev/null \
         -name "WordPerfect.mdimporter" \
         -not -path "$APP_DEST/*" \
         -not -path "*/\.*" || true)

# ── 2. Remove any existing installation ───────────────────────────────────────
if [[ -d "$APP_DEST" ]]; then
    rm -rf "$APP_DEST"
fi

# ── 3. Extract the new app ────────────────────────────────────────────────────
# Use ditto rather than unzip to preserve macOS extended attributes.
ditto -x -k "$ZIP_PATH" /Applications

# ── 4. Register with LaunchServices and Spotlight ─────────────────────────────
"$LSREG" -f "$APP_DEST"
mdimport -r "$APP_DEST/Contents/Library/Spotlight/WordPerfect.mdimporter" \
    2>/dev/null || true
