#!/usr/bin/env bash
# Save `mdatp health` fields to /run/mdatp-health/<field> for the Intune
# custom compliance script (intune/defender-compliance.sh).
#
# That script runs inside himmelblaud-tasks.service, and Defender refuses to
# answer it there: the daemon checks the calling process tree, can't read
# /proc/<himmelblaud_tasks pid>/cmdline ("Permission denied" in
# microsoft_defender_err.log), and the script sees no daemon. This runs from a
# timer outside that service instead. Each file holds the raw
# `mdatp health --field` output; the directory is replaced as a whole.
set -euo pipefail

MDATP=/usr/bin/mdatp
DEST=/run/mdatp-health
FIELDS=(
  healthy
  licensed
  org_id
  real_time_protection_enabled
  behavior_monitoring
  cloud_enabled
  definitions_status
  definitions_updated_minutes_ago
  app_version
)

# Right after boot the daemon may not answer yet; give it up to 2 minutes so
# the first snapshot isn't a false "not running".
for _ in $(seq 1 24); do
  [[ "$("${MDATP}" health --field healthy 2>/dev/null | tail -n1)" =~ ^(true|false)$ ]] && break
  sleep 5
done

tmp="$(mktemp -d "${DEST}.XXXXXX")"
trap 'rm -rf "${tmp}"' EXIT
for field in "${FIELDS[@]}"; do
  "${MDATP}" health --field "${field}" > "${tmp}/${field}" 2>/dev/null || true
done
chmod 0755 "${tmp}"
chmod 0644 "${tmp}"/*

# Swap in the new snapshot; readers see either the old or the new one.
rm -rf "${DEST}.old"
[[ -d "${DEST}" ]] && mv "${DEST}" "${DEST}.old"
mv "${tmp}" "${DEST}"
rm -rf "${DEST}.old"
trap - EXIT
