#!/usr/bin/env bash

################################################################
#
# Parallels Mac Management for SCCM
# Mac Client Unattended Installation Script
# http://www.parallels.com
#
################################################################

# Administrator Settings

# PMA Agent installer image download URL
PMA_AGENT_DMG_DOWNLOAD_URL=http://%YOUR_PMM_PROXY_URL_HERE%:8761/files/pma_agent.dmg

################################################################

PMA_AGENT_DMG_LOCAL_FILENAME=/tmp/pma_agent.$RANDOM.dmg

VER_PRODUCTNAME_STR="Parallels Mac Management for Microsoft SCCM"

MAGT_INSTALL_DIR="/Library/Parallels"
MAGT_UNATTENDED_INSTALLATION_FLAG_FILE="/tmp/pma_agent.installing.unattended"

if [ $PARALLELS_INTERNAL ]; then
    ALLOW_UNTRUSTED_FLAG="-allowUntrusted"
fi

Cleanup()
{
    hdiutil detach "/Volumes/$VER_PRODUCTNAME_STR"
    rm -f $PMA_AGENT_DMG_LOCAL_FILENAME
    rm -f $MAGT_UNATTENDED_INSTALLATION_FLAG_FILE
}

Log()
{
    echo "$@"
}


LogError()
{
    echo >&2 "Error: $@"
}

###############################################################################
# Main
###############################################################################

trap Cleanup EXIT
trap "exit 1" SIGHUP SIGINT SIGTERM SIGQUIT

# Create flag file and fill with random content
echo $PMA_AGENT_DMG_LOCAL_FILENAME > $MAGT_UNATTENDED_INSTALLATION_FLAG_FILE
if [ $? -ne 0 ]; then
	LogError "Cannot create flag file '$MAGT_UNATTENDED_INSTALLATION_FLAG_FILE'"
	exit 1
fi

Log "Downloading Mac Client installation image to $PMA_AGENT_DMG_LOCAL_FILENAME..."
curl -# -o "$PMA_AGENT_DMG_LOCAL_FILENAME" "$PMA_AGENT_DMG_DOWNLOAD_URL" || exit 1

Log "Installing Mac Client..."
hdiutil attach "$PMA_AGENT_DMG_LOCAL_FILENAME" || exit 1
installer -verbose -pkg "/Volumes/$VER_PRODUCTNAME_STR/$VER_PRODUCTNAME_STR.pkg" -target / ${ALLOW_UNTRUSTED_FLAG} || exit 1