#!/bin/bash
#
# preinstall — runs as root BEFORE the installer writes the payload.
#
# 1. Quits (gracefully, then forcibly) any running copy of the app.
# 2. Stops the running privileged helper so the upgrade is clean. The helper is
#    a demand-launched SMAppService LaunchDaemon whose binary lives INSIDE the
#    bundle, so an old instance still running from the about-to-be-replaced
#    bundle would keep serving stale code. We stop only the PROCESS — the launchd
#    registration and the user's approval are left intact — so the new helper
#    binary is demand-launched on next use without re-prompting for approval.
#    (No KeepAlive, so it will not respawn during the file swap.)
# 3. Removes the existing bundle from /Applications so the install is a clean
#    replace rather than a merge into a stale bundle.
#
# Installer script arguments: $3 is the target volume mountpoint ("/" for a
# normal install). Best-effort throughout; the script always exits 0 so a
# missing/already-stopped app or helper never aborts the install.

APP_NAME="Mac Performance Monitor"
BUNDLE_ID="uk.co.bzwrd.macperfmonitor"
HELPER_LABEL="uk.co.bzwrd.macperfmonitor.helper"
TARGET_VOLUME="${3:-/}"
APP="${TARGET_VOLUME%/}/Applications/${APP_NAME}.app"
LEGACY_APP="${TARGET_VOLUME%/}/Applications/MacPerfMonitor.app"  # pre-rename bundle

# The GUI (console) user, so the app can be told to quit in its own session.
console_user=$(/usr/bin/stat -f "%Su" /dev/console 2>/dev/null)
uid=$(/usr/bin/id -u "$console_user" 2>/dev/null)

# 1) Ask the app to quit cleanly in the user's session, then force-kill.
if [ -n "$console_user" ] && [ "$console_user" != "root" ] && [ -n "$uid" ]; then
  /bin/launchctl asuser "$uid" /usr/bin/sudo -u "$console_user" \
    /usr/bin/osascript -e "tell application id \"${BUNDLE_ID}\" to quit" >/dev/null 2>&1 || true
  /bin/sleep 1
fi
/usr/bin/pkill -f "/Applications/${APP_NAME}.app/Contents/MacOS/${APP_NAME}" 2>/dev/null || true

# 2) Stop the running helper instance (registration + approval preserved).
/bin/launchctl kill TERM "system/${HELPER_LABEL}" 2>/dev/null || true
/usr/bin/pkill -f "/Applications/${APP_NAME}.app/Contents/MacOS/MacPerfMonitorHelper" 2>/dev/null || true

# 3) Remove the existing bundle(s) for a clean install.
/bin/rm -rf "$APP"
/bin/rm -rf "$LEGACY_APP"

exit 0
