Files
rust-discovery/deploy/windows/Stop-OriginalNonstart221Pair.ps1
T
2026-11-16 16:48:24 +01:00

32 lines
2.6 KiB
PowerShell

$ErrorActionPreference='Stop'
[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false)
$p=[Console]::In.ReadLine()|ConvertFrom-Json
$case='C:\ProgramData\RustDiscoveryBootstrap\system-nonstart-221-stop'
if(Test-Path -LiteralPath $case){throw 'Existing original stop case: readback only'}
$r=Get-Content -LiteralPath 'C:\ProgramData\RustDiscovery\state\job-readiness.json' -Raw|ConvertFrom-Json
foreach($n in @('accepted','requesting','running','verifying','awaiting_reboot')){if($r.counts.$n-ne0){throw 'No active effect required'}}
if($r.counts.unknown-ne1){throw 'Only the preserved original unknown is allowed'}
$held=@()
foreach($name in @('RmmDiscoveryWindows','RmmDiscoverySystemHelper')){
$expected=$p.services.$name;$s=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'")
if($s.State-cne'Running'-or$s.ProcessId-ne$expected.pid-or$s.StartMode-cne'Auto'-or$s.StartName-cne$expected.account){throw 'Exact original live service required'}
if((Get-FileHash -LiteralPath $expected.image).Hash.ToLowerInvariant()-cne$expected.sha256){throw 'Original image required'}
$proc=Get-Process -Id $s.ProcessId;$null=$proc.Handle
if($proc.StartTime.ToUniversalTime().ToFileTimeUtc().ToString()-cne$expected.birth){throw 'Original process birth required'}
$held+=,@{name=$name;expected=$expected;process=$proc}
}
$null=New-Item -ItemType Directory -Path $case
function Write-Once($name,$v){$bytes=[Text.UTF8Encoding]::new($false).GetBytes(($v|ConvertTo-Json -Depth 15 -Compress));$f=[IO.File]::Open((Join-Path $case $name),'CreateNew','Write','Read');try{$f.Write($bytes,0,$bytes.Length);$f.Flush($true)}finally{$f.Dispose()}}
Write-Once 'intent.json' @{utc=[DateTime]::UtcNow.ToString('o');readiness=$r;input=$p}
foreach($x in $held){
$s=Get-CimInstance Win32_Service -Filter ("Name='"+$x.name+"'")
if($s.State-cne'Running'-or$s.ProcessId-ne$x.expected.pid-or$x.process.HasExited){throw 'Original held service process changed'}
Stop-Service -Name $x.name
(Get-Service -Name $x.name).WaitForStatus('Stopped',[TimeSpan]::FromSeconds(95))
if(!$x.process.WaitForExit(5000)){throw 'Original held process exit unconfirmed'}
$x.process.Dispose()
}
$out=@{schema_version=1;utc=[DateTime]::UtcNow.ToString('o');case_path=$case;both_stopped=$true;force_used=$false;original_held_process_exits_verified=$true;live_archive_sha256=$p.live_archive_sha256;original_services=$p.services;target_job_executed=$false;journal_rows_changed_by_bootstrap=$false;services=@(Get-Service RmmDiscoveryWindows,RmmDiscoverySystemHelper|Select-Object Name,@{n='state';e={[string]$_.Status}})}
Write-Once 'stopped.json' $out
$out|ConvertTo-Json -Depth 10 -Compress