#!/bin/bash
# Installed by cyberxyz-agent.pkg. Runs as root.
#
# 1.4.59+: the LaunchDaemon runs as root (UserName root in the plist), so there
# is no console-user substitution any more -- the package installs cleanly at
# the login window with nobody signed in, which is how MDM usually runs it.
# The daemon reads its machine token from
#   /Library/Application Support/CyberXYZ/machine-token
# and repairs every local user's package-manager config from it.
set -euo pipefail

PLIST=/Library/LaunchDaemons/io.cyberxyz.agent.plist
LABEL=io.cyberxyz.agent
XYZ=/usr/local/bin/xyz
SUPPORT="/Library/Application Support/CyberXYZ"
ENROLLMENT_TOKEN="$SUPPORT/enrollment-token"

chown root:wheel "$PLIST"
chmod 644 "$PLIST"

mkdir -p "$SUPPORT"
chown root:wheel "$SUPPORT"
chmod 755 "$SUPPORT"

for f in /var/log/cyberxyz-agent.log /var/log/cyberxyz-agent-error.log; do
    touch "$f"; chown root:wheel "$f"; chmod 644 "$f"
done

# Zero-touch enrollment: MDM drops the org enrollment token as a file payload
# (before or with this package). `xyz proxy setup` reads it from that path, so
# no argument carries the secret. --no-install-daemon: this package already
# ships the LaunchDaemon; we bootstrap it below. A failed enrollment must not
# fail the install -- the daemon logs "no machine token" until it is fixed.
if [[ -s "$ENROLLMENT_TOKEN" && ! -s "$SUPPORT/machine-token" ]]; then
    chmod 600 "$ENROLLMENT_TOKEN"
    if HOME=/var/root "$XYZ" proxy setup --system --no-install-daemon; then
        echo "enrolled via $ENROLLMENT_TOKEN"
    else
        echo "enrollment failed; rerun: sudo $XYZ proxy setup --system" >&2
    fi
fi

# Pre-1.4.59 installs ran a per-user LaunchAgent; one agent per machine.
for home in /Users/*; do
    agent="$home/Library/LaunchAgents/com.cyberxyz.proxy-daemon.plist"
    if [[ -f "$agent" ]]; then
        uid=$(/usr/bin/stat -f%u "$home")
        /bin/launchctl bootout "gui/$uid/com.cyberxyz.proxy-daemon" 2>/dev/null || true
        rm -f "$agent"
    fi
done

# bootout/bootstrap, not load/unload: the legacy verbs are deprecated and
# report a bare "Input/output error" on modern macOS.
/bin/launchctl bootout system/"$LABEL" 2>/dev/null || true
/bin/launchctl bootstrap system "$PLIST"
/bin/launchctl enable system/"$LABEL"

echo "$LABEL installed and running as root"
exit 0
