#!/bin/bash
# Intune macOS custom detection — exit 0 if QuilrAI Endpoint is installed.
#
# Exit-code contract (DO NOT change — Intune relies on it):
#   exit 0 + stdout output     → installed (Intune marks compliant)
#   exit 1 + stdout (anything) → not installed
#
# The stdout payload is enriched with state hints so an operator can paste
# detection output into a ticket and immediately see WHY a host failed without
# pulling the bootstrap log.
APP_BUNDLE="/Applications/QuilrAIProxy.app"
SERVICE_PLIST="/Library/LaunchDaemons/com.sentinel.agent.plist"
VER_FILE="/Library/Application Support/QuilrAI/.installed_version"
LOG_HINT="/Library/Application Support/QuilrAI/logs/postinstall-bootstrap.log"

app="absent"; daemon="absent"; ver="unknown"; loaded="no"; sysext="absent"
[[ -d "$APP_BUNDLE" ]] && app="present"
[[ -f "$SERVICE_PLIST" ]] && daemon="present"
[[ -f "$VER_FILE" ]] && ver="$(tr -d '[:space:]' < "$VER_FILE" 2>/dev/null)"
launchctl list com.quilrai.agent >/dev/null 2>&1 && loaded="yes"
systemextensionsctl list 2>/dev/null | grep -qiE 'ai\.quilr|sentinel' && sysext="present"

if [[ "$app" == "present" && "$daemon" == "present" ]]; then
    echo "Installed: v${ver:-unknown} app=$app daemon=$daemon loaded=$loaded sysext=$sysext"
    exit 0
fi

echo "Not installed: app=$app daemon=$daemon ver=${ver:-unknown} — see $LOG_HINT"
exit 1
