#!/bin/sh
# status-attribute.sh — Licenseware Collector registration state for an MDM
#
# A Jamf Pro extension attribute (script, string data type):
#   <result>registered</result>
# A Microsoft Intune custom attribute for macOS, or a Kandji or other MDM
# script that reports stdout, with --plain:
#   registered
#
# Values, from the exit code of `licenseware-collector status`:
#   registered     0  the control plane has acknowledged this Mac
#   enrolled       2  enrolled, not registered yet (the service retries)
#   absent         3  no registration state (not enrolled, or an image that
#                     has not started yet)
#   no-service     4  no LaunchDaemon
#   not-installed     no collector binary
#   error(<code>)     anything else, e.g. error(1) when status itself failed
#
# Scope the io.licenseware.collector profile (the token) to a smart group of
# Macs whose value is not "registered", so it leaves each Mac once enrolled.
# This runs plain `status`, never `status --require-healthy`: exit 5 (not
# working) never reaches it, and must not, or a backend outage would re-scope
# the token profile on every Mac at once.

set -u

BIN=/usr/local/libexec/licenseware-collector/licenseware-collector

plain=0
for arg in "$@"; do
    case "$arg" in
        --plain) plain=1 ;;
        -h|--help) sed -n '2,23s/^# \{0,1\}//p' "$0"; exit 0 ;;
        *) echo "status-attribute.sh: unknown argument: $arg" >&2; exit 2 ;;
    esac
done

if [ -x "$BIN" ]; then
    "$BIN" status >/dev/null 2>&1
    code=$?
    case "$code" in
        0) value=registered ;;
        2) value=enrolled ;;
        3) value=absent ;;
        4) value=no-service ;;
        *) value="error($code)" ;;
    esac
else
    value=not-installed
fi

if [ "$plain" -eq 1 ]; then
    echo "$value"
else
    echo "<result>$value</result>"
fi
