#!/bin/sh
# Activates a MacVisor license key on this Mac, from an MDM that runs scripts
# as root (Jamf Pro, Kandji, Intune, Mosyle).
#
# MacVisor holds its license for the whole Mac in its network helper, and the
# mvz command reaches it through the background service of the user logged in
# at the Mac, so the key is activated as that user. Run it once MacVisor has
# been opened on the Mac, at login or on a recurring check-in: when the Mac
# already has this key it says so and changes nothing, so running it often is
# fine.
#
# The key, in this order: MACVISOR_LICENSE_KEY in the environment; LICENSE_KEY
# below (for Kandji and Intune, which pass no parameters); Jamf Pro's
# parameter 4; or the first argument. The same Business key goes on every Mac
# it covers.
#
# Exit status: 0 activated, or already licensed with this key; 1 nobody is
# logged in, or MacVisor isn't in /Applications; 2 no key given; 4 MacVisor's
# background service didn't answer (MacVisor hasn't been opened on this Mac
# yet); anything else is mvz's own (see mvz help).

LICENSE_KEY=""

set -u

key="${MACVISOR_LICENSE_KEY:-}"
[ -n "$key" ] || key="$LICENSE_KEY"
if [ -z "$key" ] && [ $# -ge 4 ]; then key="$4"; fi
if [ -z "$key" ] && [ $# -ge 1 ] && [ $# -lt 4 ]; then key="$1"; fi
key=$(printf '%s' "$key" | tr -d '[:space:]')
[ -n "$key" ] || { echo "No license key given." >&2; exit 2; }

cli=/Applications/MacVisor.app/Contents/Helpers/macvisor-cli
[ -x "$cli" ] || { echo "MacVisor isn't in /Applications on this Mac." >&2; exit 1; }

user=$(/usr/bin/stat -f %Su /dev/console)
case "$user" in
  "" | root | loginwindow | _mbsetupuser)
    echo "Nobody is logged in at this Mac; run the policy again once someone is." >&2
    exit 1 ;;
esac
uid=$(/usr/bin/id -u "$user")

as_user() { /bin/launchctl asuser "$uid" /usr/bin/sudo -u "$user" "$cli" "$@"; }

# Already licensed with this key? mvz shows a key as its last four characters.
status=$(as_user license --json 2>/dev/null)
phase=$(printf '%s' "$status" | /usr/bin/plutil -extract result.phase raw -o - - 2>/dev/null)
masked=$(printf '%s' "$status" | /usr/bin/plutil -extract result.licenseKeyMasked raw -o - - 2>/dev/null | tr '[:lower:]' '[:upper:]')
last4=$(printf '%s' "$key" | tail -c 4 | tr '[:lower:]' '[:upper:]')
if [ "$phase" = licensed ]; then
  case "$masked" in
    *"$last4") echo "This Mac is already licensed with this key."; exit 0 ;;
  esac
fi

printf '%s\n' "$key" | as_user license activate -
