#!/bin/zsh --no-rcs

# Install Support App LaunchAgent
#
#
# Copyright 2024 Root3 B.V. All rights reserved.
#
# This script will create the Support App LaunchAgent and reload it when needed.
#
# THE SOFTWARE IS PROVIDED BY ROOT3 B.V. "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
# EVENT SHALL ROOT3 B.V. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
# IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

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

# LaunchAgent label
launch_agent="nl.root3.support"

# LaunchDaemon label
launch_daemon="nl.root3.support.helper"

# Install location
install_location="/Applications/Support.app"

# Directory containing this script and the LaunchAgent property list shipped
# alongside it in the package
script_directory="$(cd -- "$(dirname -- "$0")" && pwd -P)"

# Get the username of the currently logged in user
username=$(scutil <<< "show State:/Users/ConsoleUser" | awk '/Name :/ && ! /loginwindow/ { print $3 }')

# Remove "Downloaded from Internet" warning
# xattr -d -r com.apple.quarantine "${install_location}"

# Load Requirements
autoload is-at-least

# macOS Version
os_version=$(sw_vers -productVersion)

# ------------------    Gatekeeper scan    ------------------

# Perform a Gatekeeper scan. This is useful for pre-warming the cache so users 
# do not see the 'Verifying...' dialog on first launch of an application.
if is-at-least 14.0 ${os_version}; then
	gktool scan "${install_location}"
fi

# ------------------    LaunchAgent    ------------------

# Path to the LaunchAgent property list shipped alongside this script
launch_agent_plist_source="${script_directory}/${launch_agent}.plist"

# Path to the LaunchAgent property list
launch_agent_plist="/Library/LaunchAgents/${launch_agent}.plist"

# Install the LaunchAgent. The property list is a static file shipped with this
# package and is only copied into place, never generated here. Earlier versions
# created it with "defaults write", which hands the write to cfprefsd and adds
# the com.apple.quarantine extended attribute to every file it creates. launchd
# refuses to load quarantined property list files on macOS 27 and higher.
if [[ -f "${launch_agent_plist_source}" ]]; then

	# Remove any existing property list first. Overwriting in place reuses the
	# existing inode and keeps its extended attributes, including a quarantine
	# attribute left behind by an earlier version of this script.
	rm -f "${launch_agent_plist}"

	# Copy without extended attributes or resource forks. The source comes from
	# the signed and notarized package and is not quarantined, -X guarantees
	# nothing is carried over.
	cp -X "${launch_agent_plist_source}" "${launch_agent_plist}"

	# Set permissions
	chown root:wheel "${launch_agent_plist}"
	chmod 644 "${launch_agent_plist}"
else
	echo "Missing ${launch_agent_plist_source}, keeping the existing LaunchAgent"
fi

# Reload the LaunchAgent
if [[ -n "${username}" ]]; then

	# Get the username ID
	uid=$(id -u "${username}")

	# Unload the LaunchAgent
	if launchctl print "gui/${uid}/${launch_agent}" &> /dev/null ; then
		launchctl bootout gui/${uid} "/Library/LaunchAgents/${launch_agent}.plist" &> /dev/null
	fi

	# Just to be sure, kill Support App if still running
	if pgrep -x "Support" ; then
		killall -9 "Support"
	fi

	# Load the LaunchAgent
	launchctl bootstrap gui/${uid} "/Library/LaunchAgents/${launch_agent}.plist"
fi

# ------------------    Uninstall SupportHelper    ------------------

# Remove SupportHelper and LaunchDaemon if found
if [[ -f "/usr/local/bin/SupportHelper" ]]; then

	# Remove SupportHelper binary
	rm -f "/usr/local/bin/SupportHelper"

	# Unload the LaunchDaemon
	if launchctl print "system/${launch_daemon}" &> /dev/null ; then
		launchctl bootout "system/${launch_daemon}" &> /dev/null
	fi

	# Remove SupportHelper LaunchDaemon
	if [[ -f "/Library/LaunchDaemons/${launch_daemon}.plist" ]]; then
		rm -f "/Library/LaunchDaemons/${launch_daemon}.plist"
	fi
	
fi

# ------------------    PrivilegedHelperTool    ------------------

# Detect optional preference to opt-out of Privileged Helper Tool activation
privileged_helper_tool_opt_out=$(/usr/bin/osascript -l JavaScript << EOS 2>/dev/null
ObjC.unwrap($.NSUserDefaults.alloc.initWithSuiteName('nl.root3.support').objectForKey('DisablePrivilegedHelperTool'))
EOS
)

# Setup Privileged Helper Tool if not opted out
if [[ "${privileged_helper_tool_opt_out}" != "true" ]]; then
	"${install_location}/Contents/Resources/install_privileged_helper_tool.zsh"
fi