# This script is intended to be called from a Windows Provisioning Package.
# The provisioning package invokes this script the following way:
# powershell.exe -ExecutionPolicy Bypass -Command ". $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Install-SyncroAgent.ps1'))) ; Install-SyncroAgent -URL 'https://install.syncromsp.com/agent.msi'"

Function Install-SyncroAgent ([string]$URL) {

    # Exit if $URL is null or empty
    If ([string]::IsNullOrEmpty($URL)) {
        Write-Output "The URL parameter cannot be null or empty"
        Exit 1
    }

    # Exit if running without admin rights
    If (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
        Write-Output "This script must be run as an administrator"
        Exit 1
    }

    # Download and install the Syncro Agent
    $Installer = "${Env:TEMP}\SyncroInstaller.msi"
    Try { (New-Object System.Net.WebClient).DownloadFile($URL,$Installer) }
    Catch { Write-Error "The Syncro Agent installer could not be downloaded from ${URL}`n"+$_.Exception.Message ; Exit 1 }
    If ( Test-Path $Installer ) {
        Start-Process msiexec.exe -ArgumentList "/i ""${Installer}"" /qn /norestart" -Wait
        Remove-Item $Installer -Force -ErrorAction SilentlyContinue
    } Else {
        Write-Error "The Syncro Agent installer was successfully downloaded but could not be found at ""${Installer}"""
        Exit 1
    }
    Exit 0
}
