@echo off
setlocal
cls

set /a REBOOT=0

echo.
echo Configuring required services to automatically start in Safe Mode with Networking.
call :configure-service AteraAgent
call :configure-service SplashtopRemoteService

:schedule-normal-reboot
call :reset-errorlevel
echo Configuring system to reboot into Normal Mode at next reboot
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Runonce" /v "*RestartNormalMode" /t REG_SZ /d "%SystemRoot%\System32\bcdedit.exe /deletevalue {current} safeboot" /f > nul 2>&1
if %ERRORLEVEL% GTR 0 (
	set /a REBOOT=%REBOOT%+1
	echo ERROR: could not configure reboot into normal mode
)

:configure-reboot-safemodewithnetworking
call :reset-errorlevel
"%SystemRoot%\System32\bcdedit.exe" /set {current} safeboot network
if %ERRORLEVEL% GTR 0 (
	set /a REBOOT=%REBOOT%+1
	echo ERROR: could not restart into Safe Mode with Networking
)

:reboot
if %REBOOT% EQU 0 (
	shutdown /r /f /t 5
	goto :end-success
)
goto :end-error

:configure-service
call :reset-errorlevel
sc query | findstr /I "SERVICE_NAME: %*" >nul
if %ERRORLEVEL% EQU 0 (
	echo Enabling %* to startup in Safe Mode with Networking
	reg add "HKLM\SYSTEM\CurrentControlSet\Control\SafeBoot\Network\%*" /f
) else (
	set /a REBOOT=%REBOOT%+1
	echo ERROR: could not configure %* service to start in Safe Mode with Networking
)
goto :EOF

:reset-errorlevel
cmd /c "exit /b 0"
goto :EOF

:end-success
echo Successfully scheduled a reboot into Safe Mode with Networking
exit /B 0
goto :end

:end-error
echo.
echo Errors were encountered and the system will not be restarted
echo Please make sure this script is run with administrative privileges
exit /B %REBOOT%
goto :end

:end