@echo off
setlocal EnableDelayedExpansion
:: ============================================================
:: Richter Technology — Remote Agent Installer v3.1
:: Generated: 2026-05-19
:: ============================================================

:: Self-elevate to admin
net session >nul 2>&1
if %errorLevel% neq 0 (
    echo Requesting administrator privileges...
    powershell -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
    exit /b
)

set "LOGDIR=C:\ProgramData\RichterInstall"
set "LOGFILE=%LOGDIR%\install-log.txt"
set "TEMPDIR=C:\temp\richter-install"
set "BASEURL=https://install.richtertechnology.com"

mkdir "%LOGDIR%" 2>nul
mkdir "%TEMPDIR%" 2>nul

echo.
echo ============================================================
echo   Richter Technology Remote Agent Installer v3.1
echo ============================================================
echo.
echo   Log: %LOGFILE%
echo.

:: ============================================================
:: MESH AGENT — entire install done in PowerShell for reliability
:: ============================================================
echo [MESH] Installing MeshCentral remote agent...
echo.

powershell -ExecutionPolicy Bypass -Command ^
 "$ErrorActionPreference = 'Continue';" ^
 "$log = '%LOGDIR%\mesh-install.log';" ^
 "Start-Transcript $log -Force;" ^
 "Write-Host '       Cleaning up old MeshCentral agents (name-agnostic, meshagent.exe-anchored)...';" ^
 "Get-CimInstance Win32_Service | Where-Object { $_.Name -eq 'Mesh Agent' -or $_.DisplayName -eq 'Mesh Agent' -or $_.PathName -match 'meshagent\.exe' } | ForEach-Object {" ^
 "  $n = $_.Name; $bin = ($_.PathName -replace ('^'+[char]34+'?([^'+[char]34+']+\.exe).*'),'$1');" ^
 "  Write-Host ('       Found legacy agent service: ' + $n);" ^
 "  Stop-Service $n -Force -EA SilentlyContinue;" ^
 "  if ($bin -and (Test-Path $bin)) { $j = Start-Job { param($b) & $b -fulluninstall 2>$null } -ArgumentList $bin; if (-not (Wait-Job $j -Timeout 45)) { Write-Host '       (uninstall hung >45s - forcing removal)'; Stop-Job $j -EA SilentlyContinue }; Remove-Job $j -Force -EA SilentlyContinue };" ^
 "  sc.exe delete $n 2>$null | Out-Null;" ^
 "};" ^
 "Get-Process -Name 'MeshAgent','meshagent' -EA SilentlyContinue | Stop-Process -Force -EA SilentlyContinue;" ^
 "Start-Sleep 1;" ^
 "@('C:\Program Files\Mesh Agent','C:\Program Files\Richter Technology\Richter Remote','C:\ProgramData\Mesh Agent') | ForEach-Object { Remove-Item $_ -Recurse -Force -EA SilentlyContinue };" ^
 "Write-Host '       Downloading agent...';" ^
 "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;" ^
 "$meshUrl = 'https://mesh.richtertechnology.com/meshagents?id=4&meshid=' + [Uri]::EscapeDataString('qYxU7ysZLVzuS25R5leNh$RLXp0dMZohd9nLOmwbn3sb4U5jPRENH76HugxyKKu6') + '&installflags=0';" ^
 "try { Invoke-WebRequest -Uri $meshUrl -OutFile '%TEMPDIR%\meshagent.exe' -UseBasicParsing -ErrorAction Stop } catch { Write-Host \"       Download failed: $_\"; Stop-Transcript; exit 1 };" ^
 "if (-not (Test-Path '%TEMPDIR%\meshagent.exe')) { Write-Host '       ERROR: File not found after download'; Stop-Transcript; exit 1 };" ^
 "$sz = (Get-Item '%TEMPDIR%\meshagent.exe').Length;" ^
 "Write-Host \"       Downloaded $sz bytes\";" ^
 "Write-Host '       Installing service...';" ^
 "$dir = 'C:\Program Files\Mesh Agent';" ^
 "New-Item -ItemType Directory -Path $dir -Force | Out-Null;" ^
 "Copy-Item '%TEMPDIR%\meshagent.exe' \"$dir\MeshAgent.exe\" -Force;" ^
 "if (-not (Test-Path \"$dir\MeshAgent.exe\")) { Write-Host '       ERROR: File deleted by AV after copy'; Stop-Transcript; exit 1 };" ^
 "Write-Host '       File copied OK';" ^
 "$msh = @('MeshName=Richter Technology','MeshType=2','MeshID=0xA98C54EF2B192D5CEE4B6E51E6578D87F44B5E9D1D319A2177D9CB3A6C1B9F7B1BE14E633D110D1FBE87BA0C7228ABBA','ServerID=0033CBF4CE5AE05FA7E5C42B55FF7F2C775C90D69ED74CBBF3B02B41CDDEAB25F1E437F0A1C786ED1EB4305FC56838E2','MeshServer=wss://mesh.richtertechnology.com:443/agent.ashx');" ^
 "[IO.File]::WriteAllLines(\"$dir\MeshAgent.msh\", $msh);" ^
 "Write-Host '       Config written';" ^
 "$binPath = \"`\"$dir\MeshAgent.exe`\"\";" ^
 "sc.exe create 'Mesh Agent' binPath= $binPath start= auto DisplayName= 'Mesh Agent' | Out-Null;" ^
 "sc.exe description 'Mesh Agent' 'MeshCentral Agent - Remote Management by Richter Technology' | Out-Null;" ^
 "sc.exe failure 'Mesh Agent' reset= 86400 actions= restart/60000/restart/60000/restart/60000 | Out-Null;" ^
 "netsh advfirewall firewall delete rule name='Mesh Agent' 2>$null | Out-Null;" ^
 "netsh advfirewall firewall add rule name='Mesh Agent' dir=in action=allow program=\"$dir\MeshAgent.exe\" enable=yes | Out-Null;" ^
 "Write-Host '       Starting service...';" ^
 "Start-Service 'Mesh Agent' -EA SilentlyContinue;" ^
 "Start-Sleep 5;" ^
 "$svc = Get-Service 'Mesh Agent' -EA SilentlyContinue;" ^
 "if ($svc -and $svc.Status -eq 'Running') { Write-Host '       OK - Mesh Agent is RUNNING'; Stop-Transcript; exit 0 };" ^
 "Write-Host '       Service not running, trying fullinstall fallback...';" ^
 "sc.exe delete 'Mesh Agent' 2>$null;" ^
 "Start-Sleep 2;" ^
 "& \"$dir\MeshAgent.exe\" -fullinstall 2>&1 | Out-String;" ^
 "Start-Sleep 10;" ^
 "$svc2 = Get-Service 'Mesh Agent' -EA SilentlyContinue;" ^
 "if ($svc2 -and $svc2.Status -eq 'Running') { Write-Host '       OK - Mesh Agent installed via fullinstall'; Stop-Transcript; exit 0 };" ^
 "Write-Host '       FAILED - Mesh Agent could not start';" ^
 "if (-not (Test-Path \"$dir\MeshAgent.exe\")) { Write-Host '       MeshAgent.exe was DELETED by antivirus' };" ^
 "Stop-Transcript; exit 1"

if %errorLevel% equ 0 (
    set "MESH_OK=1"
) else (
    set "MESH_OK=0"
)

echo.

:: ============================================================
:: RMM AGENT — MSI first, fallback to direct binary
:: ============================================================
echo [RMM]  Installing Richter monitoring agent...
echo.

powershell -ExecutionPolicy Bypass -Command ^
 "$ErrorActionPreference = 'Continue';" ^
 "$log = '%LOGDIR%\rmm-install.log';" ^
 "Start-Transcript $log -Force;" ^
 "Write-Host '       Cleaning up old installations...';" ^
 "Stop-Service RichterAgent -Force -EA SilentlyContinue;" ^
 "if (Test-Path 'C:\Program Files\RichterAgent\richter-agent.exe') { & 'C:\Program Files\RichterAgent\richter-agent.exe' --uninstall 2>$null; Start-Sleep 2 };" ^
 "if (Get-Service RichterAgent -EA SilentlyContinue) { sc.exe delete RichterAgent 2>$null; Start-Sleep 2 };" ^
 "msiexec /x '{6A3D2F8E-9B4C-4E7A-A1D0-3F8E5C9B2A71}' /qn /norestart 2>$null;" ^
 "Remove-Item 'C:\Program Files\RichterAgent' -Recurse -Force -EA SilentlyContinue;" ^
 "Remove-Item 'C:\ProgramData\RichterAgent' -Recurse -Force -EA SilentlyContinue;" ^
 "Write-Host '       Downloading MSI...';" ^
 "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;" ^
 "try { Invoke-WebRequest -Uri '%BASEURL%/richter-rmm-generic.msi' -OutFile '%TEMPDIR%\richter-rmm.msi' -UseBasicParsing -ErrorAction Stop } catch { Write-Host \"       MSI download failed: $_\" };" ^
 "if (Test-Path '%TEMPDIR%\richter-rmm.msi') {" ^
 "  Write-Host '       Installing via msiexec...';" ^
 "  $p = Start-Process msiexec -ArgumentList '/i \"%TEMPDIR%\richter-rmm.msi\" /qn /norestart REINSTALLMODE=vomus /l*v \"%LOGDIR%\rmm-msi.log\"' -Wait -PassThru;" ^
 "  Write-Host \"       msiexec exit: $($p.ExitCode)\";" ^
 "  Start-Sleep 5;" ^
 "  $svc = Get-Service RichterAgent -EA SilentlyContinue;" ^
 "  if ($svc -and $svc.Status -eq 'Running') { Write-Host '       OK - RichterAgent is RUNNING'; Stop-Transcript; exit 0 };" ^
 "  Start-Service RichterAgent -EA SilentlyContinue; Start-Sleep 3;" ^
 "  $svc = Get-Service RichterAgent -EA SilentlyContinue;" ^
 "  if ($svc -and $svc.Status -eq 'Running') { Write-Host '       OK - RichterAgent started on retry'; Stop-Transcript; exit 0 };" ^
 "};" ^
 "Write-Host '       MSI method failed, trying direct binary...';" ^
 "New-Item -ItemType Directory -Path 'C:\Program Files\RichterAgent' -Force | Out-Null;" ^
 "New-Item -ItemType Directory -Path 'C:\ProgramData\RichterAgent' -Force | Out-Null;" ^
 "try { Invoke-WebRequest -Uri 'https://rmm.richtertechnology.com/deploy/agent-binary' -OutFile 'C:\Program Files\RichterAgent\richter-agent.exe' -UseBasicParsing -ErrorAction Stop } catch { Write-Host \"       Binary download failed: $_\"; Stop-Transcript; exit 1 };" ^
 "'{\"server_url\":\"wss://rmm.richtertechnology.com/ws/agent\",\"enroll_token\":\"dz4lyNIwLcie4gzN6U5z5oEjl8cY4AVbbV70aaBcdz4\"}' | Set-Content 'C:\ProgramData\RichterAgent\config.json' -Encoding ASCII;" ^
 "& 'C:\Program Files\RichterAgent\richter-agent.exe' --install 2>&1;" ^
 "Start-Service RichterAgent -EA SilentlyContinue; Start-Sleep 5;" ^
 "$svc = Get-Service RichterAgent -EA SilentlyContinue;" ^
 "if ($svc -and $svc.Status -eq 'Running') { Write-Host '       OK - RichterAgent installed via direct binary'; Stop-Transcript; exit 0 };" ^
 "Write-Host '       FAILED - RichterAgent could not start';" ^
 "Stop-Transcript; exit 1"

if %errorLevel% equ 0 (
    set "RMM_OK=1"
) else (
    set "RMM_OK=0"
)

echo.

:: ============================================================
:: SKYLAKE FREEZE FIX — auto-apply on older Intel CPUs
:: ============================================================
echo [FIX]  Checking CPU generation...

powershell -ExecutionPolicy Bypass -Command ^
 "$cpu = (Get-CimInstance Win32_Processor).Name;" ^
 "$apply = $false;" ^
 "if ($cpu -match 'i[357]-6|i[357]-7|Pentium.*G4|Celeron.*G3') { $apply = $true };" ^
 "if (-not $apply) { Write-Host \"       CPU: $cpu — no fix needed\"; exit 0 };" ^
 "Write-Host \"       CPU: $cpu — Skylake/Kaby Lake detected, applying freeze fix...\";" ^
 "schtasks /Change /TN '\Microsoft\Windows\PI\Secure-Boot-Update' /Disable 2>$null;" ^
 "reg add 'HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard' /v EnableVirtualizationBasedSecurity /t REG_DWORD /d 0 /f 2>$null;" ^
 "reg add 'HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity' /v Enabled /t REG_DWORD /d 0 /f 2>$null;" ^
 "reg add 'HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Power' /v HiberbootEnabled /t REG_DWORD /d 0 /f 2>$null;" ^
 "reg add 'HKLM\SOFTWARE\Policies\Microsoft\Windows\DeviceInstall\Restrictions' /v DenyDeviceIDs /t REG_DWORD /d 1 /f 2>$null;" ^
 "$gpu = Get-PnpDevice | Where { $_.FriendlyName -match 'Intel.*HD.*Graphics|Intel.*UHD.*Graphics' } | Select -First 1;" ^
 "if ($gpu) { reg add 'HKLM\SOFTWARE\Policies\Microsoft\Windows\DeviceInstall\Restrictions\DenyDeviceIDs' /v 1 /t REG_SZ /d $gpu.InstanceId /f 2>$null };" ^
 "powercfg /setactive 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c 2>$null;" ^
 "powercfg /SETACVALUEINDEX SCHEME_CURRENT SUB_PCIEXPRESS ASPM 0 2>$null;" ^
 "powercfg /SETDCVALUEINDEX SCHEME_CURRENT SUB_PCIEXPRESS ASPM 0 2>$null;" ^
 "powercfg /SETACTIVE SCHEME_CURRENT 2>$null;" ^
 "reg add 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU' /v AUOptions /t REG_DWORD /d 3 /f 2>$null;" ^
 "reg add 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate' /v TargetReleaseVersion /t REG_DWORD /d 1 /f 2>$null;" ^
 "reg add 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate' /v TargetReleaseVersionInfo /t REG_SZ /d '24H2' /f 2>$null;" ^
 "Write-Host '       Freeze fix applied. Reboot needed for full effect.'"

echo.

:: ============================================================
:: FINAL VERIFICATION
:: ============================================================
echo ============================================================
echo   Final Verification
echo ============================================================

sc query "Mesh Agent" 2>nul | findstr "RUNNING" >nul 2>&1
if %errorLevel% equ 0 (
    set "MESH_OK=1"
    echo   [OK]   MeshCentral Agent  - RUNNING
) else (
    set "MESH_OK=0"
    echo   [FAIL] MeshCentral Agent  - NOT RUNNING
)

sc query RichterAgent 2>nul | findstr "RUNNING" >nul 2>&1
if %errorLevel% equ 0 (
    set "RMM_OK=1"
    echo   [OK]   RMM Monitor Agent  - RUNNING
) else (
    set "RMM_OK=0"
    echo   [FAIL] RMM Monitor Agent  - NOT RUNNING
)

echo.
if "%MESH_OK%"=="1" if "%RMM_OK%"=="1" (
    echo   Both agents installed and running!
    rmdir /s /q "%TEMPDIR%" >nul 2>&1
    goto :finish
)
if "%MESH_OK%"=="1" (
    echo   Mesh is running. RMM had issues - check %LOGDIR%\rmm-install.log
    goto :finish
)
if "%RMM_OK%"=="1" (
    echo   RMM is running. Mesh had issues - check %LOGDIR%\mesh-install.log
    goto :finish
)
echo   Neither agent installed. Logs at %LOGDIR%

:finish
echo.
echo   Logs: %LOGDIR%
echo   Support: info@richtertechnology.com
echo ============================================================
echo.
echo   This window will close in 5 seconds...
timeout /t 5 /nobreak >nul
exit
