#!/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.0
# ==============================================================================

# 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
        echo "Timed out waiting for Dock (still in Setup Assistant?)" >&2
        exit 1
    fi
    echo "Waiting for Dock to start... (${elapsed}s elapsed)"
    sleep 5
    (( elapsed += 5 ))
done

# Exit if RosettaCheck is already running
if /usr/bin/pgrep -f "/Applications/RosettaCheck.app/Contents/MacOS/RosettaCheck" > /dev/null; then
    echo "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 "/Applications/RosettaCheck.app" ]]; do
    if (( elapsed >= 300 )); then
        echo "Timed out waiting for RosettaCheck.app" >&2
        exit 1
    fi
    echo "Waiting for RosettaCheck.app... (${elapsed}s elapsed)"
    sleep 5
    (( elapsed += 5 ))
done

echo "Found RosettaCheck.app, launching hidden in the background."
# --background: don't bring to the foreground
# --hide:       launch with the app hidden (Cmd-H equivalent at startup)
/usr/bin/open --background --hide /Applications/RosettaCheck.app
exit 0