# Make sure we're booted into Safe Mode with Networking
If ( !((Get-CimInstance -ClassName Win32_ComputerSystem).BootupState.ToLower() -eq "fail-safe with network boot") ) {
    Write-Output "Cannot run script because the system is not currently booted into Safe Mode with Networking"
    Return
}

# Download the ESET Uninstaller
Write-Output "Downloading ESET Uninstaller to: ${ESETUninstaller}"
$ESETUninstallerURL = "https://download.eset.com/com/eset/tools/installers/eset_apps_remover/latest/esetuninstaller.exe"
Download-File -URL $ESETUninstallerURL -File $ESETUninstaller
If ( !(Test-Path $ESETUninstaller) ) { Write-Error "ERROR: ESET Uninstaller could not be downloaded, this script will exit" ; Return }

# Backup network interfaces and settings
$InterfacesFile = "${Global:OutputDirectory}\interfaces.dat"
If ( Test-Path $InterfacesFile ) { Write-Output "Removing existing interface export: ${InterfacesFile}" ; Remove-Item -Path $InterfacesFile -Force }
Write-Output "Exporting interfaces to: ${InterfacesFile}"
Try { & netsh.exe -c interface dump | Out-File $InterfacesFile }
Catch { Write-Error "ERROR: Interfaces could not be exported, this script will exit" ; Return }

# Uninstall all ESET products
Write-Output "Uninstalling all ESET products"
& "cmd.exe /k ""${ESETUninstaller}"" /mode=online /force"

# Restore network interfaces and settings
If ( Test-Path $InterfacesFile ) {
    Write-Output "Restoring interfaces from export: ${InterfacesFile}"
    Try { & netsh.exe exec $InterfacesFile }
    Catch { Write-Error "ERROR: Interfaces could not be restored!" }
}

# Ensure safe mode is disabled
Write-Output "Disabling safe mode"
$command = "${Env:SystemRoot}\System32\bcdedit.exe"
$params = "/deletevalue {default} safeboot".Split(" ")
Try { & "${command}" $params }
Catch {
    If ( $_.Exception.Message -match "Element not found" ) { Write-Output "  - Safe mode has already been disabled" }
    Else { Write-Error "ERROR: could not disable safe mode, manual intervention may be required" }
}

# Reboot into normal mode
Write-Output "Rebooting into normal mode"
& "${Env:SystemRoot}\System32\shutdown.exe" -r -f -t 60 -c "Operation complete. The computer will restart in 60 seconds."




