#!/bin/bash
# Installed by cyberxyz-agent.pkg. Runs as root, also at the login window
# with nobody signed in (MDM).
#
# The LaunchDaemon runs /opt/cyberxyz/bin/xyz as root: the signed standalone
# binary this package installs, root-owned and not on PATH, so the agent never
# runs code a user account can change and never shadows the developer's own
# `xyz` (1.4.83; packages before put it in /usr/local/bin). The daemon
# reads its machine token from
#   /Library/Application Support/CyberXYZ/machine-token
# and repairs every local user's package-manager config from it.
#
# 1.4.83: on 2026-11-04 an upgrade over a loaded agent failed with
# "Bootstrap failed: 5: Input/output error". `launchctl bootout` returns
# before launchd has let the old job go, so the bootstrap right after it
# failed, `set -e` stopped the script, the installer reported a failure (no
# receipt) and the agent was left NOT loaded. Now: wait until the old job is
# gone, enable, bootstrap with retries, and accept only a job whose program is
# this package's binary.
#
# Exit status: non-zero only when the agent could not be loaded after the
# retries, the binary does not start, or its folders are not root's. A failed
# install is what MDM and the Installer app must see then: MDM retries the
# policy on its next check-in and the Installer window says so, while an exit
# 0 would leave a receipt for an agent that is not running and nothing would
# retry. The payload is in place either way, and the message names the
# recovery command.
#
# Tests (xyz-cli/tests/test_postinstall.py) run this as a normal user with
# CYBERXYZ_POSTINSTALL_TEST=1, which replaces launchctl, chown, codesign,
# stat, sleep and the paths. The hook is ignored as root.
set -uo pipefail
PATH=/usr/bin:/bin:/usr/sbin:/sbin
export PATH

PLIST=/Library/LaunchDaemons/io.cyberxyz.agent.plist
LABEL=io.cyberxyz.agent
XYZ=/opt/cyberxyz/bin/xyz
LEGACY_XYZ=/usr/local/bin/xyz
SUPPORT="/Library/Application Support/CyberXYZ"
LOG_DIR=/var/log
USERS_DIR=/Users
OPT=/opt
LAUNCHCTL=/bin/launchctl
CHOWN=/usr/sbin/chown
SLEEP=/bin/sleep
STAT=/usr/bin/stat
CODESIGN=/usr/bin/codesign
if [[ "${CYBERXYZ_POSTINSTALL_TEST:-}" == "1" && "$(/usr/bin/id -u)" != "0" ]]; then
    PLIST="${T_PLIST:-$PLIST}"; XYZ="${T_XYZ:-$XYZ}"; SUPPORT="${T_SUPPORT:-$SUPPORT}"
    LOG_DIR="${T_LOG_DIR:-$LOG_DIR}"; USERS_DIR="${T_USERS_DIR:-$USERS_DIR}"; OPT="${T_OPT:-$OPT}"
    LAUNCHCTL="${T_LAUNCHCTL:-$LAUNCHCTL}"; CHOWN="${T_CHOWN:-$CHOWN}"
    SLEEP="${T_SLEEP:-$SLEEP}"; STAT="${T_STAT:-$STAT}"
    LEGACY_XYZ="${T_LEGACY_XYZ:-$LEGACY_XYZ}"; CODESIGN="${T_CODESIGN:-$CODESIGN}"
fi
ENROLLMENT_TOKEN="$SUPPORT/enrollment-token"
BOOTOUT_WAIT_TENTHS=150   # 15 s, polled every half second
BOOTSTRAP_TRIES=3
REQUIREMENT='identifier "io.cyberxyz.agent" and anchor apple generic and certificate leaf[subject.OU] = "75B8U98CJA"'

say() { echo "cyberxyz-agent: $*"; }
fail() { echo "cyberxyz-agent: $*" >&2; exit 1; }

# The program launchd has loaded for the agent ("" when not loaded).
loaded_program() { "$LAUNCHCTL" print "system/$LABEL" 2>/dev/null | sed -n 's/^[[:space:]]*program = //p' | head -1; }
loaded() { "$LAUNCHCTL" print "system/$LABEL" >/dev/null 2>&1; }

# Owned by root with no group or world write.
root_only() {
    local owner mode
    read -r owner mode < <("$STAT" -f '%u %Lp' "$1" 2>/dev/null || echo "x x")
    [[ "$owner" == "0" && "$mode" =~ ^[0-7]+$ ]] && (( (8#$mode & 8#022) == 0 ))
}

# --- 1. files and folders: root's, nobody else can write them ---------------
bin_dir=$(dirname "$XYZ")
base_dir=$(dirname "$bin_dir")                      # /opt/cyberxyz
# /opt first, before anything below it is touched (re-review of 1.4.83);
# /opt/cyberxyz and its bin must be real folders, never links to elsewhere.
root_only "$OPT" || fail "$OPT must belong to root with no group or world write; not loading the agent"
for d in "$base_dir" "$bin_dir"; do
    [[ -L "$d" ]] && fail "$d is a link; it must be a folder only root can change. Not loading the agent"
    mkdir -p "$d"; "$CHOWN" root:wheel "$d" || true; chmod 755 "$d"
done
for d in "$base_dir" "$bin_dir"; do
    root_only "$d" || fail "$d must belong to root with no group or world write; not loading the agent"
done
"$CHOWN" root:wheel "$PLIST" "$XYZ" || fail "could not set the owner of $PLIST and $XYZ"
chmod 644 "$PLIST"
chmod 755 "$XYZ"
mkdir -p "$SUPPORT"
"$CHOWN" root:wheel "$SUPPORT" || true
chmod 755 "$SUPPORT"
for f in "$LOG_DIR/cyberxyz-agent.log" "$LOG_DIR/cyberxyz-agent-error.log"; do
    touch "$f"; "$CHOWN" root:wheel "$f" || true; chmod 644 "$f"
done
# The enrollment token is root's alone, whether or not this run enrolls.
if [[ -e "$ENROLLMENT_TOKEN" ]]; then
    "$CHOWN" root:wheel "$ENROLLMENT_TOKEN" || true
    chmod 600 "$ENROLLMENT_TOKEN"
fi

# --- 2. the binary must start (a signing problem shows up here, not as a crash loop)
if ! version=$(cd / && "$XYZ" --version 2>&1); then
    fail "$XYZ does not start, so the agent was not loaded: ${version:0:400}"
fi
say "$version"

# --- 3. 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 ships the LaunchDaemon and
# loads it below. A failed enrollment does not fail the install: the agent
# logs "no machine token" until it is fixed.
if [[ -s "$ENROLLMENT_TOKEN" && ! -s "$SUPPORT/machine-token" ]]; then
    if (cd / && HOME=/var/root "$XYZ" proxy setup --system --no-install-daemon </dev/null); then
        say "enrolled from $ENROLLMENT_TOKEN"
    else
        echo "cyberxyz-agent: enrollment failed; rerun: sudo $XYZ proxy setup --system" >&2
    fi
fi

# --- 4. one agent per machine: drop pre-1.4.59 per-user LaunchAgents ---------
for home in "$USERS_DIR"/*; do
    agent="$home/Library/LaunchAgents/com.cyberxyz.proxy-daemon.plist"
    if [[ -f "$agent" ]]; then
        uid=$("$STAT" -f%u "$home")
        "$LAUNCHCTL" bootout "gui/$uid/com.cyberxyz.proxy-daemon" 2>/dev/null || true
        rm -f "$agent"
    fi
done

# --- 5. load the agent ------------------------------------------------------
# bootout/bootstrap, not load/unload (deprecated; "Input/output error").
if loaded; then
    "$LAUNCHCTL" bootout "system/$LABEL" 2>/dev/null || true
    waited=0
    while loaded; do
        if (( waited >= BOOTOUT_WAIT_TENTHS )); then
            say "the old agent is still registered after $((BOOTOUT_WAIT_TENTHS / 10)) s; trying anyway"
            break
        fi
        "$SLEEP" 0.5
        waited=$((waited + 5))
    done
fi
# Enable first: a job disabled earlier (launchctl disable) refuses to bootstrap.
"$LAUNCHCTL" enable "system/$LABEL" 2>/dev/null || true
tries=0
while :; do
    "$LAUNCHCTL" bootstrap system "$PLIST" || true
    program=$(loaded_program)
    if [[ "$program" == "$XYZ" ]]; then
        break
    fi
    if [[ -n "$program" ]]; then
        # launchd still runs the OLD definition: drop it and try again.
        "$LAUNCHCTL" bootout "system/$LABEL" 2>/dev/null || true
    fi
    tries=$((tries + 1))
    if (( tries >= BOOTSTRAP_TRIES )); then
        fail "launchd did not load the agent ($XYZ) after $BOOTSTRAP_TRIES tries${program:+ (it still runs $program)}. The files are installed; load it with:
  sudo launchctl enable system/$LABEL && sudo launchctl bootstrap system $PLIST"
    fi
    "$SLEEP" 2
done

# --- 6. only now: drop the binary an earlier package put on PATH --------------
# Packages before 1.4.83 put it in /usr/local/bin, where it shadowed the
# developer's own xyz. Removed only when it is OUR signed binary (a regular
# file meeting the CyberXYZ designated requirement), never a pip, pipx or
# Homebrew xyz, nor a link someone made.
if [[ -f "$LEGACY_XYZ" && ! -L "$LEGACY_XYZ" ]] \
        && "$CODESIGN" --verify --strict -R="$REQUIREMENT" "$LEGACY_XYZ" >/dev/null 2>&1; then
    rm -f "$LEGACY_XYZ" && say "removed the old $LEGACY_XYZ (the agent now runs $XYZ)"
fi

say "$LABEL installed and running as root ($XYZ)"
exit 0
