@echo off
setlocal
set "BASE=C:\ProgramData\EVA\WorkspaceAgent"
set "SCRIPT=%BASE%\eva-home-monitor.ps1"
set "RUNNER=%BASE%\eva-home-monitor-runner.cmd"
set "TMP=%TEMP%\eva-home-monitor.ps1"
set "TASK=EVA Workspace HOME Monitor"
set "URL=https://home.nikolskoe3.ru/downloads/eva-home-monitor.ps1?v=0.1.3"
set "SHA=28440397ab0a7f8c476ab84b2b7209077a00530336f3b87666eef21ab90aba23"

net session >nul 2>&1
if errorlevel 1 (
  echo ERROR: run this installer as Administrator.
  exit /b 1
)

if not exist "%BASE%\secret.dpapi" (
  echo ERROR: HOME credential file not found.
  exit /b 2
)

curl.exe --ssl-no-revoke --connect-timeout 10 --max-time 60 -fL "%URL%" -o "%TMP%"
if errorlevel 1 (
  echo ERROR: monitor agent download failed.
  exit /b 3
)

for /f "usebackq delims=" %%H in (`powershell.exe -NoProfile -NonInteractive -Command "(Get-FileHash -LiteralPath '%TMP%' -Algorithm SHA256).Hash.ToLowerInvariant()"`) do set "ACTUAL=%%H"
if /i not "%ACTUAL%"=="%SHA%" (
  echo ERROR: SHA256 mismatch.
  echo EXPECTED=%SHA%
  echo ACTUAL=%ACTUAL%
  exit /b 4
)

copy /y "%TMP%" "%SCRIPT%" >nul
if errorlevel 1 (
  echo ERROR: cannot install monitor agent.
  exit /b 5
)

> "%RUNNER%" echo @echo off
>>"%RUNNER%" echo echo ==== EVA HOME MONITOR START %%DATE%% %%TIME%% ====^>^>"%BASE%\monitor-startup.log"
>>"%RUNNER%" echo powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "%SCRIPT%" ^>^>"%BASE%\monitor-startup.log" 2^>^&1
>>"%RUNNER%" echo echo EXITCODE=%%ERRORLEVEL%%^>^>"%BASE%\monitor-startup.log"

schtasks.exe /End /TN "%TASK%" >nul 2>&1
schtasks.exe /Delete /TN "%TASK%" /F >nul 2>&1
schtasks.exe /Create /TN "%TASK%" /SC ONSTART /RU SYSTEM /RL HIGHEST /TR "cmd.exe /d /c %RUNNER%" /F >nul
if errorlevel 1 (
  echo ERROR: cannot create scheduled task.
  exit /b 6
)

schtasks.exe /Run /TN "%TASK%" >nul
if errorlevel 1 (
  echo ERROR: cannot start scheduled task.
  exit /b 7
)

timeout /t 4 /nobreak >nul
echo.
echo EVA HOME MONITOR INSTALLED
echo SCRIPT=%SCRIPT%
echo SHA256=%ACTUAL%
schtasks.exe /Query /TN "%TASK%" /FO LIST /V | findstr /I /C:"Status:" /C:"Last Run Result:"
echo.
echo Open EVA Workspace and wait for MONITOR ONLINE.
exit /b 0
