#!/bin/sh
# MacVisor's license on this Mac, for an inventory attribute: a Jamf Pro
# extension attribute (FORMAT=jamf, the default) or an Intune custom attribute
# for macOS (set FORMAT=plain). Runs as root, and reads the license as the user
# logged in at the Mac sees it (`mvz license --json`).
#
# Prints one line, for example:
#   licensed, subscription, 5 Macs, lease until 2026-12-05
# The phase is licensed, noLicense, expired, revoked, unverified, tamperBlocked
# or damagedCopy; the tier is one-time (Pro), subscription (Business or
# Enterprise) or trial; the lease date is how long the Mac keeps working
# without reaching the licensing server. Without a user logged in, or before
# MacVisor has been opened, it says so instead.

FORMAT=jamf

say() {
  if [ "$FORMAT" = plain ]; then echo "$1"; else echo "<result>$1</result>"; fi
  exit 0
}

cli=/Applications/MacVisor.app/Contents/Helpers/macvisor-cli
[ -x "$cli" ] || say "Not installed"

user=$(/usr/bin/stat -f %Su /dev/console)
case "$user" in
  "" | root | loginwindow | _mbsetupuser) say "Nobody logged in" ;;
esac
uid=$(/usr/bin/id -u "$user")

json=$(/bin/launchctl asuser "$uid" /usr/bin/sudo -u "$user" "$cli" license --json 2>/dev/null)
field() { printf '%s' "$json" | /usr/bin/plutil -extract "result.$1" raw -o - - 2>/dev/null; }

phase=$(field phase)
[ -n "$phase" ] || say "Unknown: MacVisor's background service didn't answer"

out="$phase"
tier=$(field tier)
[ -n "$tier" ] && out="$out, $tier"
macs=$(field maxDevices)
case "$macs" in
  "") ;;
  1) out="$out, 1 Mac" ;;
  *) out="$out, $macs Macs" ;;
esac
lease=$(field leaseExpiresAt | cut -c1-10)
[ -n "$lease" ] && out="$out, lease until $lease"
say "$out"
