#!/bin/bash
# Install the full CLI's root hourly updater without restarting an updater
# that may be the parent of this package transaction, and bootstrap the
# per-user scheduler LaunchAgent for the console user.

set -euo pipefail

UPDATE_DAEMON_PLIST=/Library/LaunchDaemons/com.runlayer.cli.update.plist
SCHEDULE_AGENT_PLIST=/Library/LaunchAgents/com.runlayer.cli.schedule.plist
SCHEDULE_AGENT_LABEL=com.runlayer.cli.schedule
DESKTOP_APP=/Applications/Runlayer.app
PRODUCT_MARKER=/usr/local/lib/runlayer/product

chmod 755 /usr/local/lib/runlayer/runlayer/runlayer
chown root:wheel "$PRODUCT_MARKER"
chmod 644 "$PRODUCT_MARKER"
if [ -x "$DESKTOP_APP/Contents/MacOS/Runlayer" ]; then
    chown -R root:wheel "$DESKTOP_APP"
    chmod 755 "$DESKTOP_APP/Contents/MacOS/Runlayer"
fi
chown root:wheel "$UPDATE_DAEMON_PLIST"
chmod 644 "$UPDATE_DAEMON_PLIST"
chown root:wheel "$SCHEDULE_AGENT_PLIST"
chmod 644 "$SCHEDULE_AGENT_PLIST"

# No bootout: during self-update this postinstall runs beneath the loaded job.
# bootstrap is idempotent and harmlessly fails when that job is already loaded.
launchctl bootstrap system "$UPDATE_DAEMON_PLIST" 2>/dev/null || true

CONSOLE_USER=$(/usr/bin/stat -f '%Su' /dev/console 2>/dev/null || true)
if [ -n "$CONSOLE_USER" ] && [ "$CONSOLE_USER" != "root" ] && [ "$CONSOLE_USER" != "loginwindow" ]; then
    CONSOLE_UID=$(/usr/bin/id -u "$CONSOLE_USER")

    # Scheduler agent: unlike the update daemon, this agent is never the parent
    # of the install transaction (it runs in the user GUI domain), so bootout +
    # bootstrap picks up a refreshed plist on upgrades. No-op at loginwindow
    # (outer guard); launchd loads the agent at the next login instead.
    launchctl bootout "gui/${CONSOLE_UID}/${SCHEDULE_AGENT_LABEL}" 2>/dev/null || true
    launchctl bootstrap "gui/${CONSOLE_UID}" "$SCHEDULE_AGENT_PLIST" 2>/dev/null || true

    # Stop a previous tray when replacing either product. For desktop installs,
    # reopening registers runlayer:// and SMAppService.mainApp for later logins.
    /usr/bin/pkill -TERM -u "$CONSOLE_UID" -x Runlayer 2>/dev/null || true
    for _ in 1 2 3 4 5 6 7 8 9 10; do
        if ! /usr/bin/pgrep -u "$CONSOLE_UID" -x Runlayer >/dev/null; then
            break
        fi
        /bin/sleep 0.2
    done
    /usr/bin/pkill -KILL -u "$CONSOLE_UID" -x Runlayer 2>/dev/null || true
    if [ -x "$DESKTOP_APP/Contents/MacOS/Runlayer" ]; then
        /bin/launchctl asuser "$CONSOLE_UID" \
            /usr/bin/sudo -u "$CONSOLE_USER" \
            /usr/bin/open "$DESKTOP_APP" >/dev/null 2>&1 || true
    fi
fi

exit 0
