#!/bin/zsh
#
# ==============================================================================
# Rosetta Check - Post-Install Launcher
# ==============================================================================
#
# Purpose:  Triggers the first launch of Rosetta Check after MDM deployment so
#           the app can register its login item via SMAppService. Once
#           registered, the accompanying configuration profile ensures the
#           login item remains approved and locked on at every subsequent login.
#
# Behaviour:
#           1. Waits for Dock.app to be running so we don't fire during Setup
#              Assistant / pre-login (no UI session yet).
#           2. Exits cleanly if RosettaCheck is already running.
#           3. Waits up to 5 minutes for /Applications/RosettaCheck.app to
#              appear (handles race between script execution and app install).
#           4. Launches the app hidden and in the background via
#              `open --background --hide`.
#
# Deployment:
#           MDM shell script payload (Intune, Jamf, Kandji, etc.)
#           Run as signed-in user: Yes
#           Frequency:             Once (or every login if preferred)
#
# Companion profile:
#           RosettaCheck-MDM.mobileconfig (managed prefs + servicemanagement
#           login item approval by TeamIdentifier 8352865GK4).
#
# Author:   Neil Johnson
# Source:   https://github.com/neiljohn-mac/rosettacheck (TBC)
# Version:  1.2
# ==============================================================================
#
# Diagnostics:
#   All status messages are written to BOTH the script's stdout/stderr (so
#   Intune captures them in "Detection output") AND the macOS unified log
#   via syslog with a unique tag. macOS's bundled BSD logger(1) does NOT
#   support the GNU --subsystem / --category options, so we identify our
#   lines by a unique tag instead. To inspect on a deployed Mac:
#
#       log show --predicate 'eventMessage CONTAINS "rosettacheck-launcher"' \
#           --info --last 1h
#
#   For live tailing during a fresh enrolment:
#
#       log stream --predicate 'eventMessage CONTAINS "rosettacheck-launcher"' \
#           --info
# ==============================================================================

readonly LOG_TAG="rosettacheck-launcher"
readonly APP_PATH="/Applications/RosettaCheck.app"
readonly APP_BIN="${APP_PATH}/Contents/MacOS/RosettaCheck"

log_info() {
    print -r -- "$*"
    /usr/bin/logger -t "$LOG_TAG" -p user.notice -- "$*"
}

log_err() {
    print -r -- "$*" >&2
    /usr/bin/logger -t "$LOG_TAG" -p user.error -- "ERROR: $*"
}

log_info "Starting RosettaCheck launcher (uid=$(id -u) user=$(id -un) host=$(hostname -s))"

# Wait for Dock to be running. If Dock isn't up, the user is still in
# Setup Assistant (or no user session exists yet) and launching a UI app
# would be wrong / would race the setup flow. Cap at 30 minutes so the
# Intune sidecar doesn't hang forever on a stuck enrolment.
elapsed=0
while ! /usr/bin/pgrep -x Dock > /dev/null; do
    if (( elapsed >= 1800 )); then
        log_err "Timed out waiting for Dock after ${elapsed}s (still in Setup Assistant?)"
        exit 1
    fi
    log_info "Waiting for Dock to start... (${elapsed}s elapsed)"
    sleep 5
    (( elapsed += 5 ))
done
log_info "Dock is running, proceeding."

# Exit if RosettaCheck is already running
if /usr/bin/pgrep -f "$APP_BIN" > /dev/null; then
    log_info "RosettaCheck is already running, nothing to do."
    exit 0
fi

# Wait up to 5 minutes for the app to be installed
elapsed=0
while [[ ! -d "$APP_PATH" ]]; do
    if (( elapsed >= 300 )); then
        log_err "Timed out waiting for ${APP_PATH} after ${elapsed}s"
        exit 1
    fi
    log_info "Waiting for ${APP_PATH}... (${elapsed}s elapsed)"
    sleep 5
    (( elapsed += 5 ))
done

# Sanity-check the bundle before we try to launch it
if [[ ! -x "$APP_BIN" ]]; then
    log_err "App bundle present but binary missing or not executable: $APP_BIN"
    exit 1
fi
app_version=$(/usr/bin/defaults read "${APP_PATH}/Contents/Info" CFBundleShortVersionString 2>/dev/null || echo "unknown")
log_info "Found ${APP_PATH} (version ${app_version}), launching via AppleScript 'launch' (no activate)."

# Launch via AppleScript's `launch` verb rather than `open`.
#
# `open --background --hide` only sets the initial activation state — if the app
# calls NSApp.activate(...) or presents a window in applicationDidFinishLaunching
# (very common for SwiftUI WindowGroup apps) it will steal focus anyway.
#
# AppleScript distinguishes between `launch` (start the process WITHOUT bringing
# it forward and WITHOUT sending the standard 'open application' Apple Event)
# and `activate` (bring forward). `launch` goes through a different LaunchServices
# code path that some self-activating apps respect. It is also the documented
# Apple way of starting a UI-element / agent app silently.
#
# If the app STILL appears in the foreground after this, the cause is app-side
# (the app is calling NSApp.activate(...) itself, or a WindowGroup is presenting
# a window on launch). No shell flag can override that — the fix has to be in
# the app's launch code.
launch_output=$(/usr/bin/osascript -e 'tell application "RosettaCheck" to launch' 2>&1)
launch_rc=$?
if (( launch_rc != 0 )); then
    log_err "AppleScript launch failed (rc=${launch_rc}): ${launch_output}"
    log_info "Falling back to 'open --background --hide'."
    if ! /usr/bin/open --background --hide "$APP_PATH"; then
        rc=$?
        log_err "'open' fallback also failed with exit code ${rc}"
        exit "$rc"
    fi
fi

# Verify the process actually stayed up. `open` returns 0 the moment LaunchServices
# accepts the request, even if the app crashes on launch (bad entitlement, quarantine,
# missing Rosetta, etc.) — which is exactly the silent-failure mode we hit in v1.0.
sleep 3
if /usr/bin/pgrep -f "$APP_BIN" > /dev/null; then
    pid=$(/usr/bin/pgrep -f "$APP_BIN" | head -1)
    log_info "RosettaCheck is running (pid=${pid}). Done."
    exit 0
else
    log_err "RosettaCheck did NOT stay running 3s after launch. Check unified log:"
    log_err "  log show --predicate 'process == \"RosettaCheck\"' --last 5m"
    log_err "  log show --predicate 'subsystem == \"com.apple.syspolicy\"' --last 5m | grep -i rosetta"
    exit 1
fi