#!/bin/sh
set -eu
data='/Library/Application Support/LanUps'
token="$data/agent.token"
install -d -m 0755 -o root -g wheel "$data"
if [ ! -f "$token" ]; then LANUPS_AGENT_TOKEN="$token" /usr/local/libexec/lanups/agent/LanUps.Agent --provision; fi
chmod 0600 "$token"

user=$(/usr/bin/stat -f '%Su' /dev/console)
case "$user" in root|loginwindow|_mbsetupuser|'') user='';; esac
if [ -n "$user" ]; then
    uid=$(id -u "$user")
    home=$(/usr/bin/dscl . -read "/Users/$user" NFSHomeDirectory | sed 's/^NFSHomeDirectory: //')
    case "$home" in /*) ;; *) echo 'Cannot determine the desktop account home' >&2; exit 1;; esac
    chmod -N "$token"
    chmod +a "user:$user allow read" "$token"
    sudo -u "$user" mkdir -p "$home/Library/LaunchAgents"
    sudo -u "$user" install -m 0644 /usr/local/libexec/lanups/local.lanups.desktop.plist "$home/Library/LaunchAgents/local.lanups.desktop.plist"
fi

launchctl bootstrap system /Library/LaunchDaemons/local.lanups.agent.plist
if [ -n "$user" ] && launchctl print "gui/$uid" >/dev/null 2>&1; then
    launchctl bootstrap "gui/$uid" "$home/Library/LaunchAgents/local.lanups.desktop.plist"
fi
