#!/bin/zsh --no-rcs

# Support App Extension - App Auto-Patch Pending Apps Dialog
#
# Opens App Auto-Patch 4's own deferral dialog for the person at the Mac,
# through its appautopatch://show-deferral-prompt link, then refreshes the
# pending-updates count Extension (aap_pending_updates.zsh).
#
# The dialog is the one App Auto-Patch opens by itself when updates are due:
# it lists each pending app with its installed and new version, and has an
# install button, a deferral menu and a defer button. App Auto-Patch checks
# the pending apps again just before it opens, and applies its settings as
# usual: deadlines, the deferral menu, button text, AppTitle and the dialog
# timeout. Deferring here counts as a deferral, as in that dialog. After this
# cycle's patching is complete, App Auto-Patch shows its dashboard instead.
#
# REQUIREMENTS:
# - App Auto-Patch 4.0.0 (105) or later
# - Deployed as a Privileged Script referenced by an Extension's Action, via a
#   Support App Configuration Profile (ActionType: PrivilegedScript)
#
# App Auto-Patch 4 has no equivalent of 3.x's --workflow-install-now, which
# patched without a dialog, so this is the only Action script for 4.0.

# ------------------    edit the variables below this line    ------------------

# Extension ID - must match the ExtensionID configured for the pending-updates
# Extension in the Support App Configuration Profile
extension_id="aap_pending_updates"

# Path to the companion script that refreshes the pending-updates count.
# Update this if you deploy aap_pending_updates.zsh to a different location.
refresh_script_path="/Library/Application Support/AppAutoPatch/SupportApp/aap_pending_updates.zsh"

# ---------------------    do not edit below this line    ----------------------

# Support App preference plist
preference_file_location="/Library/Preferences/nl.root3.support.plist"

# App Auto-Patch's patch status, written by its root helper
compliance_file="/Library/Application Support/AppAutoPatch/compliance.json"

app_bundle_id="xyz.techitout.appAutoPatch"
app_process_name="App Auto-Patch"
prompt_url="appautopatch://show-deferral-prompt"

refresh_count() {
    if [[ -x "${refresh_script_path}" ]]; then
        "${refresh_script_path}"
    else
        echo "ERROR: ${refresh_script_path} not found or not executable." >&2
        # Fall back to at least clearing the loading indicator so the tile
        # doesn't get stuck spinning if the refresh script is missing.
        defaults write "${preference_file_location}" "${extension_id}_loading" -bool false
    fi
}

# App Auto-Patch runs in the session of the person at the Mac, and this script
# runs as root, so open the link as that person.
console_user=$(/usr/bin/stat -f %Su /dev/console)
if [[ -z "${console_user}" || "${console_user}" == "root" || "${console_user}" == "loginwindow" ]]; then
    echo "No one is logged in at the Mac; not opening App Auto-Patch."
    refresh_count
    exit 0
fi
console_uid=$(/usr/bin/id -u "${console_user}")

run_as_console_user() {
    /bin/launchctl asuser "${console_uid}" /usr/bin/sudo -u "${console_user}" "$@"
}

# With nothing pending, App Auto-Patch has no dialog to show. Refresh the
# tile, which then reads "Up to Date".
pending_count=$(/usr/bin/plutil -extract pendingCount raw -o - "${compliance_file}" 2> /dev/null)
[[ "${pending_count}" == <-> ]] || pending_count=0
if [[ "${pending_count}" -eq 0 ]]; then
    echo "No pending updates in ${compliance_file}; not opening the dialog."
    refresh_count
    exit 0
fi

# Show a brief loading state on the Support App tile while App Auto-Patch
# opens the dialog.
defaults write "${preference_file_location}" "${extension_id}_loading" -bool true
defaults write "${preference_file_location}" "${extension_id}" -string "Opening App Auto-Patch…"

# The link is handled by a running App Auto-Patch. If it isn't running, start
# it and give it a moment to finish launching before sending the link.
if ! /usr/bin/pgrep -u "${console_uid}" -x "${app_process_name}" > /dev/null; then
    echo "App Auto-Patch isn't running for ${console_user}; starting it."
    run_as_console_user /usr/bin/open -b "${app_bundle_id}"
    for _ in {1..30}; do
        /usr/bin/pgrep -u "${console_uid}" -x "${app_process_name}" > /dev/null && break
        sleep 1
    done
    sleep 5
fi

run_as_console_user /usr/bin/open "${prompt_url}"
open_exit=$?
if [[ "${open_exit}" -ne 0 ]]; then
    echo "ERROR: could not open ${prompt_url} for ${console_user} (exit ${open_exit})." >&2
fi

# Refresh the pending-updates count. The dialog stays open on its own, and the
# count catches up the next time the popover appears.
refresh_count

exit "${open_exit}"
