#!/bin/bash
#set -x

############################################################################################
## Custom installation script for ISL Light via Microsoft Intune
## Version 1.0.0
## ISL Online
############################################################################################

# Variables

deployment_link="https://ICP_ADDRESS/download/ISLLight?platform=mac&cmdline=--setup-and-exit"
# ISL Light Custom Silent Deployment link - Please change ICP_ADDRESS to match your scenario.

appname="ISL Light"                                                        				# The name of the application that will be deployed
app="ISL Light.app"                                                        				# The actual name of the App once installed
logdir="/Library/Logs/Microsoft/Intune"            					 					# 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_light_dmg () {
    echo "$(date) - Starting download of ISL Light DMG"
    echo "$(date) - Downloading ISL Light 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 Light DMG"
    else
         echo "$(date) - Failed to download ISL Light"
         exit 1
    fi
}
function install_isl_light () {
    echo "$(date) - Installing ISL Light"

    volume="$tempdir/$appname"
    echo "$(date) - Mounting DMG"
    hdiutil attach -quiet -nobrowse -mountpoint "$volume" "$tempfile"

    if [[ -d "/Applications/$app" ]]; then
        echo "$(date) - Uninstall ISL Light"
        rm -rf /Applications/ISL\ Light.app
    fi

    echo "$(date) - Starting installer from the mounted DMG"
    "$volume"/ISL\ Light.app/Contents/MacOS/isllight
	
    echo "$(date) - Unmounting ISL Light DMG"
    hdiutil detach -quiet "$volume"

    if [[ -a "/Applications/$app" ]]; then

        echo "$(date) - ISL Light Installed"
        echo "$(date) - Cleaning Up temporary files"
        rm -rf "$tempfile"
        exit 0
    else
        echo "$(date) - Failed to install ISL Light"
        rm -rf "$tempdir"
        exit 1
    fi
}

# main function

start_logging
download_isl_light_dmg
install_isl_light