#!/bin/bash
#
# postinstall — runs as root AFTER the installer writes the payload.
#
# Launches the freshly installed app in the logged-in user's GUI session. A bare
# `open` here would run as root (wrong session, wrong owner), so it is wrapped in
# `launchctl asuser <uid> sudo -u <user>` to land in the console user's session
# and run as that user.
#
# Launching also refreshes the privileged helper: the app re-registers the
# SMAppService daemon on launch, and the next connection demand-launches the new
# helper binary (the old instance having been stopped in preinstall).
#
# Installer script arguments: $3 is the target volume mountpoint ("/" for a
# normal install). Best-effort; always exits 0.

APP_NAME="Mac Performance Monitor"
TARGET_VOLUME="${3:-/}"
APP="${TARGET_VOLUME%/}/Applications/${APP_NAME}.app"

console_user=$(/usr/bin/stat -f "%Su" /dev/console 2>/dev/null)
uid=$(/usr/bin/id -u "$console_user" 2>/dev/null)

# Only launch when a real user is at the GUI (skip the login window and
# unattended/system installs).
if [ -n "$console_user" ] && [ "$console_user" != "root" ] && [ -n "$uid" ]; then
  /bin/launchctl asuser "$uid" /usr/bin/sudo -u "$console_user" \
    /usr/bin/open "$APP" || true
fi

exit 0
