# Exit early if apps are running
$ExitEarly = $false
$AppNames = @()
If ( IsRunning -Name 'revit' )       { $ExitEarly = $true ; $AppNames.Add('Revit') }
If ( IsRunning -Name 'sketchup' )    { $ExitEarly = $true ; $AppNames.Add('SketchUp') }
If ( IsRunning -Name 'archicad' )    { $ExitEarly = $true ; $AppNames.Add('ArchiCAD') }
If ( IsRunning -Name 'autocad' )     { $ExitEarly = $true ; $AppNames.Add('AutoCAD') }
If ( IsRunning -Name 'rhino' )       { $ExitEarly = $true ; $AppNames.Add('Rhino') }
If ( IsRunning -Name 'vectorworks' ) { $ExitEarly = $true ; $AppNames.Add('VectorWorks') }
If ( $ExitEarly ) { Write-Output "Installation cannot continue because the following apps are running: ${AppNames}." ; Return }

# Path to the MSI installer
$URL = 'https://enscape-installer.chaosgroup.com/installer.enscape.io/Enscape-4.0.2.11.exe'

# Set path to temp directory
$TEMPDIR = '{0}enscape-installer' -f (Get-TempPath)

# Recursively delete $TEMPDIR if it already exists
If ( Test-Path $TEMPDIR ) {
    Write-Output """${TEMPDIR}"" already exists and will be deleted"
    Try { Remove-Item -Path $TEMPDIR -Recurse -Force -ErrorAction SilentlyContinue }
    Catch { Write-Error $_.Exception.Message }
}

# Create $TEMPDIR
Write-Output "Creating: ${TEMPDIR}"
Try { New-Item -Path $TEMPDIR -ItemType Directory -Force -ErrorAction Stop }
Catch { Write-Error $_.Exception.Message ; Return }

# Write $CONFIG to config.xml
$CONFIG = @'
<DefValues>
 <Value Name="INSTALL_SKETCHUP" DataType="value">1</Value>
 <Value Name="STDROOT" DataType="value">C:\Program Files\Enscape</Value>
 <Value Name="INSTALL_RHINO" DataType="value">1</Value>
 <Value Name="INSTALL_ARCHICAD" DataType="value">1</Value>
 <Value Name="LOCALE" DataType="value">en-US</Value>
 <Value Name="INSTALL_REVIT" DataType="value">1</Value>
 <Value Name="INSTALL_VECTORWORKS" DataType="value">1</Value>
</DefValues>

'@
Try { $CONFIG | WriteToFile_UTF8NoBOM -FilePath "${TEMPDIR}\config.xml" }
Catch { Write-Output "Cannot write configuration file! This script will exit." ; Write-Error $_.Exception.Message ; Return }

# Download the installer
$Installer = "${TEMPDIR}\$(Split-Path $URL -Leaf)"
Download-File -URL $URL -File $Installer

# Install package
If ( !(Test-Path $Installer) ) { Write-Output "Cannot download installer! This script will exit." ; Return }
Write-Output "Installing Enscape from ""${Installer}"""
Start-Process $Installer -ArgumentList "-gui=0 -acceptEULA -configFile=""${TEMPDIR}\config.xml"" -quiet=1 -ignoreErrors=1" -Wait

# Delete the installer
Write-Output "Deleting temp directory and its contents"
Try { Remove-Item -Path $TEMPDIR -Recurse -Force -ErrorAction SilentlyContinue }
Catch { Write-Error $_.Exception.Message }
