#!/bin/bash
# Audit a Watcher installation for Iru. Runs as root.
# Exit 0 when Watcher is installed and healthy. Any other status asks
# Iru to run remediate-macos.sh.

set -uo pipefail

readonly LAUNCH_LABEL="ai.apolloresearch.watcher"
# Must match the port remediate-macos.sh pins the daemon to (see its WATCHER_PORT).
readonly WATCHER_PORT="8228"

needs_install() { printf '[watcher-audit] %s\n' "$*"; exit 1; }

console_user() {
    local u
    u="$(/usr/bin/stat -f%Su /dev/console 2>/dev/null || true)"
    case "$u" in
        ""|root|loginwindow|_mbsetupuser|_securityagent) printf '' ;;
        *) printf '%s' "$u" ;;
    esac
}

# Drop to the target user when we're root; run directly when we already are that
# user (the WATCHER_MDM_USER test path).
run_as_user() {
    local user="$1"; shift
    if [ "$(id -u)" -eq 0 ]; then
        /usr/bin/sudo -u "$user" -H "$@"
    else
        "$@"
    fi
}

# WATCHER_MDM_USER overrides the auto-detected console user for local testing.
user="${WATCHER_MDM_USER:-$(console_user)}"
if [ -z "$user" ]; then
    # There is no per-user installation to check until someone logs in.
    printf '[watcher-audit] no console user; deferring checks to the next enforce after login\n'
    exit 0
fi

home="$(/usr/bin/dscl . -read "/Users/$user" NFSHomeDirectory 2>/dev/null | awk '{print $2}')"
[ -n "$home" ] || needs_install "could not resolve home for '$user'"
# The executable and its runtime files are installed under the user's ~/.local directory.
readonly LIB_DIR="$home/.local/share/apollo-watcher"
readonly WATCHER_BIN="$LIB_DIR/watcher/watcher"

[ -x "$WATCHER_BIN" ] || needs_install "Watcher binary missing at $WATCHER_BIN"
# A present executable with a missing _internal/ would pass the version check but
# fail to launch, so check the runtime tree too.
[ -d "$LIB_DIR/watcher/_internal" ] || needs_install "Watcher runtime tree missing at $LIB_DIR/watcher/_internal"

# Read the version from the binary because the installer does not create a version file.
installed_version="$(run_as_user "$user" "$WATCHER_BIN" --version 2>/dev/null | awk '{print $NF}')"
[ -n "$installed_version" ] || needs_install "Watcher binary at $WATCHER_BIN did not report a version"

run_as_user "$user" "$WATCHER_BIN" doctor hooks >/dev/null 2>&1 \
    || needs_install "Watcher hook check failed; Iru should run remediate-macos.sh"

plist="$home/Library/LaunchAgents/${LAUNCH_LABEL}.plist"
[ -f "$plist" ] || needs_install "login agent not installed at $plist"

# Check the agent is loaded in the user's GUI session, not just that the plist exists.
uid="$(/usr/bin/id -u "$user")"
/bin/launchctl print "gui/$uid/$LAUNCH_LABEL" >/dev/null 2>&1 \
    || needs_install "login agent $LAUNCH_LABEL not loaded for $user"

/usr/bin/curl -fsS -o /dev/null "http://localhost:${WATCHER_PORT}/api/health" \
    || needs_install "daemon not answering on localhost:${WATCHER_PORT}"

printf '[watcher-audit] installed and healthy (v%s)\n' "$installed_version"
exit 0
