# NOTE: The $CONFIG variable must be set by the calling script

# Check whether agent is already installed
If ( Test-Path "${Env:ProgramFiles}\ESET\RemoteAdministrator\Agent\ERAAgent.exe" ) {
    
    # End the script if no errors are found in the status log
    If ( !(Select-String -Path "${Env:ProgramData}\ESET\RemoteAdministrator\Agent\EraAgentApplicationData\Logs\status.html" -CaseSensitive -Pattern 'Error:' -Quiet) ) {
        Microsoft.Powershell.Utility\Write-Output "ESET agent is already installed and no errors were found. This script will now exit."
        Return
    }
    
    Write-Output "ESET agent is already installed, but errors were found in the status log. This script will continue and attempt to reinstall the agent."
}

# Set path to temp directory
$TEMPDIR = '{0}eset-protect-deployment' -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 install_config.ini
Try { $CONFIG | WriteToFile_UTF8NoBOM -FilePath "${TEMPDIR}\install_config.ini" }
Catch { Write-Output "Cannot write configuration file! This script will exit." ; Write-Error $_.Exception.Message ; Return }

# Get bitness of endpoint and set $AGENTNAME
If ( Is64bit ) { $AGENTNAME = "agent_x64.msi" } Else { $AGENTNAME = "agent_x86.msi" }

# Download the installer
$INSTALLER = "${TEMPDIR}\${AGENTNAME}"
$URL = 'https://download.eset.com/com/eset/apps/business/era/agent/latest/{0}' -f $AGENTNAME
Write-Output "Downloading ESET Management Agent"
Download-File -URL $URL -File $INSTALLER

# Install the app
Write-Output "Installing ESET Management Agent from ""${INSTALLER}"""
Try { Start-Process "msiexec.exe" -ArgumentList "/i ${INSTALLER} /qn /norestart /log installer.log" -Wait }
Catch { Write-Error $_.Exception.Message }

# 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 }
