#! /bin/bash -s --

# This script will check if user-level MDM is enabled

tmpdir=$(mktemp -d -t com.parallels.pmm.EnableUserMdm.discovery)
trap "rm -rf $tmpdir" 0 2 3 15

PMMCTL='/Library/Parallels/pma_agent.app/Contents/MacOS/pmmctl'

# Exit codes
EXIT_CODE_GENERAL_ERROR=1

WriteResult() { echo "$@"; }

WriteLog() { echo >&2 "$@"; }

IsMacClientAtLeast()
{
    local min="$1"

    local tmpfile="$tmpdir/macclient-pkg-info.plist"
    rm -f "$tmpfile"

    # Read pkg info to tmpfile
    /usr/sbin/pkgutil --pkg-info-plist com.parallels.pkg.pma.agent > "$tmpfile"
    if [ $? -ne 0 ]; then
        WriteLog "Failed to get the MacClient package info"
        return $EXIT_CODE_GENERAL_ERROR
    fi

    # Extract version
    local ver
    ver=$(/usr/libexec/PlistBuddy -c "Print pkg-version" "$tmpfile")
    if [ $? -ne 0 ]; then
        WriteLog "Failed to get the MacClient version"
        return $EXIT_CODE_GENERAL_ERROR
    fi

    test "$(printf '%s\n' "$min" "$ver" | sort -V | head -n1)" = "$min"
}

IsUserMdmEnabled()
{
    local tmpfile="$tmpdir/user-mdm-status.plist"
    rm -f "$tmpfile"

    # Run pmmctl
    "$PMMCTL" user-mdm-status > "$tmpfile"
    if [ $? -ne 0 ]; then
        WriteLog "Failed to get the user-level MDM status:"
        WriteLog $(<"$tmpfile")
        return $EXIT_CODE_GENERAL_ERROR
    fi

    # Extract status
    local enabled
    enabled=$(/usr/libexec/PlistBuddy -c "Print UserMdmEnabled" "$tmpfile")
    if [ $? -ne 0 ]; then
        WriteLog "Failed to get the UserMdmEnabled value"
        WriteLog $(<"$tmpfile")
        return $EXIT_CODE_GENERAL_ERROR
    fi

    echo $enabled
}


if ! IsMacClientAtLeast "8.7"; then
    WriteLog "MacClient version 8.7 or higher is required"
    exit $EXIT_CODE_GENERAL_ERROR
fi

enabled=$(IsUserMdmEnabled)
if [ $? -ne 0 ]; then
    exit $EXIT_CODE_GENERAL_ERROR
fi

if [ "$enabled" = 'true' ]; then
    WriteLog "User-level MDM is enabled"
    WriteResult "Yes"
else
    WriteLog "User-level MDM is disabled"
    WriteResult "No"
fi
