@echo off
setlocal EnableExtensions
title RC Link - Windows Agent Setup
set "BASE=https://rc.hlutharyea.com/downloads"
set "EXPECTED=E6F33B1359B563FC764FCC4D6941D9A6C0DE7B4B277E832D2C4C589F579054D1"
set "WORK=%TEMP%\RcLinkSetup"

net session >nul 2>&1
if errorlevel 1 (
  echo Requesting administrator rights...
  powershell -NoProfile -ExecutionPolicy Bypass -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
  exit /b
)

echo.
echo  RC Link - Windows Agent Setup
echo  ============================================
echo  This downloads about 58 MB, verifies it,
echo  installs the agent as a Windows service,
echo  then shows the address and password.
echo.
choice /c YN /n /m "Continue? [Y/N] "
if errorlevel 2 exit /b 1
echo.

if exist "%WORK%" rd /s /q "%WORK%"
mkdir "%WORK%" >nul 2>&1
if not exist "%WORK%" goto :fail

call :download 001
if errorlevel 1 goto :fail
call :download 002
if errorlevel 1 goto :fail
call :download 003
if errorlevel 1 goto :fail

echo.
echo Joining parts...
copy /b "%WORK%\RcAgent-Setup.zip.001"+"%WORK%\RcAgent-Setup.zip.002"+"%WORK%\RcAgent-Setup.zip.003" "%WORK%\RcAgent-Setup.zip" >nul
if errorlevel 1 goto :fail

echo Verifying SHA-256...
set "ACTUAL="
for /f "usebackq delims=" %%H in (`powershell -NoProfile -Command "(Get-FileHash -LiteralPath '%WORK%\RcAgent-Setup.zip' -Algorithm SHA256).Hash"`) do set "ACTUAL=%%H"
if not defined ACTUAL goto :fail
echo   %ACTUAL%
if /i not "%ACTUAL%"=="%EXPECTED%" goto :hashfail

echo Extracting...
powershell -NoProfile -Command "Expand-Archive -LiteralPath '%WORK%\RcAgent-Setup.zip' -DestinationPath '%WORK%\pkg' -Force"
if errorlevel 1 goto :fail

echo.
echo Starting installer...
echo.
call "%WORK%\pkg\install.cmd"
set "RC=%errorlevel%"
if "%RC%"=="0" (
  echo.
  echo Cleaning up temporary files...
  rd /s /q "%WORK%" 2>nul
)
exit /b %RC%

:download
set "PART=%~1"
echo.
echo Downloading part %PART% ...
if exist "%SystemRoot%\System32\curl.exe" (
  "%SystemRoot%\System32\curl.exe" -L --fail --retry 3 --connect-timeout 20 -o "%WORK%\RcAgent-Setup.zip.%PART%" "%BASE%/RcAgent-Setup.zip.%PART%"
) else (
  powershell -NoProfile -ExecutionPolicy Bypass -Command "Invoke-WebRequest -UseBasicParsing -Uri '%BASE%/RcAgent-Setup.zip.%PART%' -OutFile '%WORK%\RcAgent-Setup.zip.%PART%'"
)
if errorlevel 1 (
  echo Download failed for part %PART%.
  exit /b 1
)
exit /b 0

:hashfail
echo.
echo ERROR: SHA-256 does not match. The download is incomplete or corrupted.
echo Delete the temporary folder and run this file again.
pause
exit /b 1

:fail
echo.
echo ERROR: Setup failed. Check the messages above.
if exist "%WORK%" echo Temporary files kept in: %WORK%
pause
exit /b 1
