#!/bin/bash
# Installed by cyberxyz-agent.pkg. Runs as root.
#
# The LaunchDaemon ships with placeholder UserName/HOME because the daemon must
# run AS the console user -- it reads ~/.npmrc for the machine token and ~/.xyz
# for config, which as root resolve to /var/root and find nothing. Running at
# boot without login is the reason this is a daemon; running as the user is the
# reason it still finds its config.
set -euo pipefail

PLIST=/Library/LaunchDaemons/io.cyberxyz.agent.plist
LABEL=io.cyberxyz.agent

# Console user, not $USER: under an MDM/pkg install this script's $USER is root.
CONSOLE_USER=$(/usr/bin/stat -f%Su /dev/console)
if [[ -z "$CONSOLE_USER" || "$CONSOLE_USER" == "root" ]]; then
    # Installed at the login window with nobody signed in. Leave the daemon
    # unloaded rather than wiring it to root, where it would run but never find
    # a machine token. It loads at the next boot after a user exists.
    echo "no console user at install time; leaving $LABEL unconfigured"
    exit 0
fi
CONSOLE_HOME=$(/usr/bin/dscl . -read "/Users/$CONSOLE_USER" NFSHomeDirectory | awk '{print $2}')

/usr/bin/sed -i '' \
    -e "s|__XYZ_RUN_AS_USER__|$CONSOLE_USER|g" \
    -e "s|__XYZ_RUN_AS_HOME__|$CONSOLE_HOME|g" \
    "$PLIST"

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

# Logs are written by the daemon running as the console user, so they must be
# writable by that user -- otherwise launchd fails to spawn it entirely.
for f in /var/log/cyberxyz-agent.log /var/log/cyberxyz-agent-error.log; do
    touch "$f"; chown "$CONSOLE_USER" "$f"; chmod 644 "$f"
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 $CONSOLE_USER"
exit 0
