#!/bin/bash
#set -x

############################################################################################
## Custom installation script for ISL AlwaysOn via SimpleMDM
## Version 1.0.0
## ISL Online
############################################################################################

# Variables

deployment_link="https://ICP_ADDRESS/download/ISLAlwaysOn?platform=mac&cmdline=%2FVERYSILENT+grant_silent+%22GRANT_BLOB%22+password+%22URL_ENCODED_PASSWORD%22" 
# ISL AlwaysOn Custom Silent Deployment link - Please change ICP_ADDRESS, GRANT_BLOB and URL_ENCODED_PASSWORD to match your scenario.

appname="ISLAlwaysOn"                                                        				# The name of the application that will be deployed
app="ISLAlwaysOn.app"                                                        				# The actual name of the App once installed
logdir="/Library/Managed Installs/Logs"            					 						# The location of the logs

# Generated variables
tempdir=$(mktemp -d)
log="$logdir/$appname.log"                                               					# The location of the script log file

function start_logging() {
    if [[ ! -d "$logdir" ]]; then
        echo "$(date) - Creating folder to store logs"
        mkdir -p "$logdir"
    fi
    exec &> >(tee -a "$log")    
}
function download_isl_always_on_dmg () {
    echo "$(date) - Starting download of ISL AlwaysOn DMG"
    echo "$(date) - Downloading ISL AlwaysOn DMG"

    cd "$tempdir"
    curl -f -s --connect-timeout 30 --retry 5 --retry-delay 60 -L -J -O "$deployment_link"
    if [ $? == 0 ]; then
	        tempSearchPath="$tempdir/*"
            for f in $tempSearchPath; do
                tempfile=$f
            done
            echo "$(date) - Successfully downloaded ISL AlwaysOn DMG"
    else
         echo "$(date) - Failed to download ISL AlwaysOn"
         exit 1
    fi
}
function install_isl_always_on () {
    echo "$(date) - Installing ISL AlwaysOn"

    volume="$tempdir/$appname"
    echo "$(date) - Mounting DMG"
    hdiutil attach -quiet -nobrowse -mountpoint "$volume" "$tempfile"

    if [[ -d "/Applications/ISLAlwaysOn/$app" ]]; then
        echo "$(date) - Uninstall ISL AlwaysOn"
        "/Applications/ISLAlwaysOn/ISLAlwaysOnUninstall.app/Contents/MacOS/uninstall.sh"
    fi

    echo "$(date) - Starting installer from the mounted DMG"
    "$volume"/Install\ ISL\ AlwaysOn.app/Contents/MacOS/islalwayson
	
    echo "$(date) - Unmounting ISL AlwaysOn DMG"
    hdiutil detach -quiet "$volume"

    if [[ -a "/Applications/ISLAlwaysOn/$app" ]]; then

        echo "$(date) - ISL AlwaysOn Installed"
        echo "$(date) - Cleaning Up temporary files"
        rm -rf "$tempfile"
        exit 0
    else
        echo "$(date) - Failed to install ISL AlwaysOn"
        rm -rf "$tempdir"
        exit 1
    fi
}

# main function

start_logging
download_isl_always_on_dmg
install_isl_always_on