#!/bin/bash
# postinstall — runs as root after pkgbuild installs payload.
#
# The .pkg installs:
#   /usr/local/lib/runlayer/aiwatch/              PyInstaller onedir bundle
#   /usr/local/bin/aiwatch                        symlink → bundle exe
#   /Library/LaunchAgents/com.runlayer.aiwatch.plist  scan-on-schedule agent
#
# This script:
#   1. Marks the binary executable.
#   2. Sets the LaunchAgent file ownership to root:wheel (required for
#      /Library/LaunchAgents — launchd refuses to load otherwise).
#   3. Bootstraps the LaunchAgent into the current console user's GUI domain
#      (gui/<uid>) so it starts immediately without waiting for the next
#      login. Idempotent on upgrade (bootout first, then bootstrap).
#
# Errors in the launchctl step are tolerated (|| true): the agent will load
# on next login regardless, and we don't want to fail the whole install when
# the user is on the loginwindow (no console user → stat fails).

set -euo pipefail

chmod 755 /usr/local/lib/runlayer/aiwatch/aiwatch

AGENT_PLIST=/Library/LaunchAgents/com.runlayer.aiwatch.plist
chown root:wheel "$AGENT_PLIST"
chmod 644 "$AGENT_PLIST"

CONSOLE_UID=$(stat -f %u /dev/console 2>/dev/null || echo "")
if [ -n "$CONSOLE_UID" ] && [ "$CONSOLE_UID" != "0" ]; then
    launchctl bootout "gui/${CONSOLE_UID}/com.runlayer.aiwatch" 2>/dev/null || true
    launchctl bootstrap "gui/${CONSOLE_UID}" "$AGENT_PLIST" 2>/dev/null || true
fi

exit 0
