#!/bin/bash
set -x

# Only proceed if we are installing on the booted volume
[[ $3 != "/" ]] && exit 0

# Let's play python roulette, and choose from some popular options, in this order:
#  1. python.org https://www.python.org/downloads/
#  2. MacAdmins https://github.com/macadmins/python
#  3. Munki https://github.com/munki/munki
# If none of these are on disk, then fall back to Apple's system python,
# which can be installed via the Command Line Tools.

# "What about python 2, which Apple still ships," you ask?
#  Outset does not support python 2, which was sunsetted on Jan 1, 2020.
#  See https://www.python.org/doc/sunset-python-2/.
#  If you choose to continue to use python 2, you'll want to create the symlink via other means,
#  with something like: /bin/ln -s /usr/bin/python /usr/local/outset/python3

OUTSET_PYTHON=/usr/local/outset/python3
ORG_PYTHON=/usr/local/bin/python3
MACADMINS_PYTHON=/usr/local/bin/managed_python3
MUNKI_MUNKI_PYTHON=/usr/local/munki/munki-python
MUNKI_PYTHON=/usr/local/munki/python
SYSTEM_PYTHON=/usr/bin/python3

# Delete existing symlink
[[ -L "${OUTSET_PYTHON}" ]] && /bin/rm "${OUTSET_PYTHON}"

if [[ -L "${ORG_PYTHON}" ]]; then
    /bin/ln -s "${ORG_PYTHON}" "${OUTSET_PYTHON}"
elif [[ -L "${MACADMINS_PYTHON}" ]]; then
    /bin/ln -s "${MACADMINS_PYTHON}" "${OUTSET_PYTHON}"
elif [[ -L "${MUNKI_MUNKI_PYTHON}" ]]; then
    /bin/ln -s "${MUNKI_MUNKI_PYTHON}" "${OUTSET_PYTHON}"
elif [[ -L "${MUNKI_PYTHON}" ]]; then
    /bin/ln -s "${MUNKI_PYTHON}" "${OUTSET_PYTHON}"
else
    /bin/ln -s "${SYSTEM_PYTHON}" "${OUTSET_PYTHON}"
fi

# Load the LaunchDaemons
/bin/launchctl load /Library/LaunchDaemons/com.github.outset.boot.plist
/bin/launchctl load /Library/LaunchDaemons/com.github.outset.cleanup.plist
/bin/launchctl load /Library/LaunchDaemons/com.github.outset.login-privileged.plist

# Load the LaunchAgents

user=$(/bin/echo "show State:/Users/ConsoleUser" | /usr/sbin/scutil | /usr/bin/awk '/Name :/&&!/loginwindow/{print $3}')
console_user_uid=$(stat -f%u /dev/console)
[[ -z "$user" ]] && exit 0
/bin/launchctl asuser "$console_user_uid" /bin/launchctl load /Library/LaunchAgents/com.github.outset.login.plist
/bin/launchctl asuser "$console_user_uid" /bin/launchctl load /Library/LaunchAgents/com.github.outset.on-demand.plist

exit 0
