# Specify URL to "Backup for Windows" agent installer
$ECB_WIN_URL = 'https://console.msp360.com/api/build/download?urlParams=OEFsMzhldm1SbjhaSDhBc2VtYkpUREM3Y2pJSzg0REU4dkVtR1pHREkxMGFFUk9qZXJnSXk5SUF0ei8wZlZOWTBzNG1zVDV0ckVMdStZVzBsam5uZklMVnZLeTBMVmxGNWt4VDhSMzNIL3VVV2gxVnJrZjh6Zy9SQ0hMNWlVbVBTUjdvUlBHSlgyR0tWQ1FzemxESjBqcVJUUDVzcy8vdlFBa3VrWVdmY1hCVUxUODVHWWlwTnlpL3lDRWFza2RXTHduSEsxN0ZkSkQ0cGZRWk9WNkVyQT09&brandId=fb8308e2-448a-4645-a5f6-a3632a7e57f4'

# Specify URL to "Backup Virtual Machine Edition" agent installer
$ECB_VMM_URL = 'https://console.msp360.com/api/build/download?urlParams=OEFsMzhldm1SbjhaSDhBc2VtYkpUREM3Y2pJSzg0REU4dkVtR1pHREkxMGFFUk9qZXJnSXk5SUF0ei8wZlZOWUpYM2xDY3ErMkpOVGpuWTRISDNFcFRFdWRibDgvTm8vUDhpWndON3kzaHNScng2OVp4bmJvQ3ZZaC9qSVRFdm5tVVdVNEhmZzU1M0xMd25reXQ1SUNXMWk0ZmNJMGplTVkybGJ2VHhTQUd2ZW9KdjhFTDhWbmhuVXd5VXR1YnE5R2ptZkMxbEhKbksya1pKR1NoRnZnZz09&brandId=fb8308e2-448a-4645-a5f6-a3632a7e57f4'

# Set the correct download URL and agent edition
switch ( $Edition.ToLower() ) {
    'server'  { $URL = $ECB_WIN_URL; $AgentEdition = 'baremetal' }
    'desktop' { $URL = $ECB_WIN_URL; $AgentEdition = 'desktop'   }
    'vm'      { $URL = $ECB_VMM_URL; $AgentEdition = 'vmedition' }
    default   { $URL = $ECB_WIN_URL; $AgentEdition = 'desktop'   }
}

# Install and import additional Powershell module
Import-MSP360Module

# Exit this script if the agent is already installed
If ( $(Get-MBSAgent -ErrorAction SilentlyContinue) ) {
    Microsoft.Powershell.Utility\Write-Output "Backup agent is already installed. This script will now exit."
    Return
}

#
# The URL is now too long to pass as a variable to other functions and cmdlets, so this is a workaround to download the file
#

# Make sure the URL is valid
$StatusCode = [System.Net.WebRequest]::Create($URL).GetResponse().StatusCode
If ( !(($StatusCode -ge 200) -and ($StatusCode -lt 400)) ) { Write-Output "URL cannot be reached (status code ${StatusCode}): ${URL}" ; Return }

# Make a local file to download to
$Installer = '{0}EmberkomCloudBackup.exe' -f (Get-TempPath)

# Delete previous local file if it exists
If ( Test-Path $Installer ) { Write-Output "Deleting previously downloaded file: ${Installer}" ; Remove-Item $Installer -Force -ErrorAction SilentlyContinue }

# Download the file
Try { (New-Object System.Net.WebClient).DownloadFile($URL,$Installer) }
Catch { Write-Error $_.Exception.Message ; Remove-Item $Installer -Force -ErrorAction SilentlyContinue }

# Make sure the file exists
If ( !(Test-Path $Installer) ) { Write-Output "There was a problem downloading the file, this script will not continue" ; Return }

#
# End the workaround
#

# Install the agent
Write-Output "Installing Emberkom Cloud Backup agent"
Try { Start-Process "${Installer}" -ArgumentList "/S" -Wait }
Catch { Write-Error $_.Exception.Message }

# Add backup user to installed product
Write-Output "Adding backup user account: ${MSP360Username}"
Try { Add-MBSUserAccount -User $MSP360Username -Password $(ConvertTo-SecureString -string $MSP360Password -AsPlainText -Force) }
Catch { Write-Error $_.Exception.Message }

# Wait a few seconds to let the agent check-in
Start-Sleep -Seconds 10

# Set the agent edition
# Note: the product edition must be set *after* the user is added
Write-Output "Setting Emberkom Cloud Backup agent edition to ""$AgentEdition"""
Try {
    Switch ([string]::IsNullOrEmpty($MasterPassword)) {
        $true  { Set-MBSAgentSetting -Edition $AgentEdition -Verbose }
        $false { Set-MBSAgentSetting -Edition $AgentEdition -MasterPassword $(ConvertTo-SecureString -String $MasterPassword -AsPlainText -Force) -Verbose }
    }
}
Catch { Write-Error $_.Exception.Message }

# Delete $Installer
If ( Test-Path $Installer ) { Write-Output "Deleting downloaded file: ${Installer}" ; Remove-Item $Installer -Force -ErrorAction SilentlyContinue }

# Delete the desktop icon
If ( Test-Path "${Env:PUBLIC}\Desktop\Emberkom Backup.LNK" ) { Remove-Item -Path "${Env:PUBLIC}\Desktop\Emberkom Backup.LNK" -Force -ErrorAction SilentlyContinue }
If ( Test-Path "${Env:PUBLIC}\Desktop\Emberkom Cloud Backup.LNK" ) { Remove-Item -Path "${Env:PUBLIC}\Desktop\Emberkom Cloud Backup.LNK" -Force -ErrorAction SilentlyContinue }
