& { $ErrorActionPreference = 'Stop' $ProgressPreference = 'SilentlyContinue' function Invoke-DarwinCommand { param([string]$Executable, [ValidateSet('--status', '--exit', '--diagnose')][string]$Command) $info = New-Object System.Diagnostics.ProcessStartInfo $info.FileName = $Executable $info.Arguments = $Command $info.UseShellExecute = $false $info.CreateNoWindow = $true $info.RedirectStandardOutput = $true $info.RedirectStandardError = $true $info.StandardOutputEncoding = [Text.Encoding]::UTF8 $info.StandardErrorEncoding = [Text.Encoding]::UTF8 $child = [Diagnostics.Process]::Start($info) try { $stdout = $child.StandardOutput.ReadToEndAsync() $stderr = $child.StandardError.ReadToEndAsync() if (-not $child.WaitForExit(12000)) { # Only this short-lived CLI child is stopped, never a running agent. try { $child.Kill() } catch { } throw "Команда $Command не ответила за 12 секунд. Проверьте старый агент и уровень прав." } [pscustomobject]@{ ExitCode = $child.ExitCode; Output = $stdout.GetAwaiter().GetResult(); Error = $stderr.GetAwaiter().GetResult() } } finally { $child.Dispose() } } function Convert-DarwinStatus { param($Reply) if ($Reply.ExitCode -ne 0) { return $null } try { $parsed = $Reply.Output | ConvertFrom-Json if (-not $parsed.Success -or -not $parsed.Data.ProcessId) { throw 'Нет PID агента' } return $parsed.Data } catch { throw 'Агент вернул некорректный статус. Установка остановлена; работающий процесс не завершён.' } } function Test-DarwinStartup { param($Status, [int]$ProcessId, [string]$Version) if ($null -eq $Status) { return $false } if ($Status.ProcessId -ne $ProcessId -or $Status.Version -ne $Version) { throw 'На команды отвечает другой экземпляр или старая версия DarwinPC. Выполните --diagnose.' } return ($Status.InitializationComplete -eq $true) } function Invoke-DarwinInstall { if (-not [Environment]::Is64BitOperatingSystem -or [Environment]::OSVersion.Platform -ne 'Win32NT') { throw 'DarwinPC требует Windows x64.' } $releaseVersion = '0.8.4' $expectedHash = 'B6BD32C6AE3F6DE4A9213E4E1499A03B7530A01070AC16BA310C249970BE7FF6' $downloadUri = 'https://h.firstend.ru/downloads/darwin/0.8.4/DarwinPC.exe' $installDirectory = Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) ('Orion\DarwinPC\' + $releaseVersion) $executable = Join-Path $installDirectory 'DarwinPC.exe' [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 New-Item -ItemType Directory -Path $installDirectory -Force | Out-Null if (-not (Test-Path -LiteralPath $executable) -or (Get-FileHash -LiteralPath $executable -Algorithm SHA256).Hash -ne $expectedHash) { $downloadFile = Join-Path $installDirectory ([Guid]::NewGuid().ToString('N') + '.download') try { Write-Host 'Скачивание DarwinPC...' Invoke-WebRequest -UseBasicParsing -Uri $downloadUri -OutFile $downloadFile if ((Get-FileHash -LiteralPath $downloadFile -Algorithm SHA256).Hash -ne $expectedHash) { throw 'Контрольная сумма DarwinPC не совпала. Загруженный файл не будет запущен.' } Move-Item -LiteralPath $downloadFile -Destination $executable -Force } finally { if (Test-Path -LiteralPath $downloadFile) { Remove-Item -LiteralPath $downloadFile -Force } } } $previous = Convert-DarwinStatus (Invoke-DarwinCommand $executable '--status') if ($previous) { Write-Host "Завершение предыдущего агента (PID $($previous.ProcessId))..." $previousAgent = Get-Process -Id $previous.ProcessId -ErrorAction SilentlyContinue try { $exitReply = Invoke-DarwinCommand $executable '--exit' if ($exitReply.ExitCode -ne 0) { throw "Не удалось штатно завершить агент: $($exitReply.Error)" } if ($previousAgent -and -not $previousAgent.WaitForExit(15000)) { throw 'Предыдущий агент ещё завершается. Повторите установку позже; принудительная остановка не выполнялась.' } } finally { if ($previousAgent) { $previousAgent.Dispose() } } } $session = [Diagnostics.Process]::GetCurrentProcess().SessionId $conflicts = @(Get-Process -Name DarwinPC,OrionPcDemo -ErrorAction SilentlyContinue | Where-Object { $_.SessionId -eq $session }) if ($conflicts.Count -gt 0) { $ids = ($conflicts | ForEach-Object { "$($_.ProcessName) PID=$($_.Id)" }) -join ', ' throw "Остался процесс: $ids. Закройте его под той же учётной записью и с тем же уровнем прав. Повторный запуск не заменяет старый процесс." } $portOwners = @() try { $portOwners += @(Get-NetUDPEndpoint -ErrorAction Stop | Where-Object LocalPort -eq 45821 | Select-Object -ExpandProperty OwningProcess) $portOwners += @(Get-NetTCPConnection -State Listen -ErrorAction Stop | Where-Object LocalPort -eq 45822 | Select-Object -ExpandProperty OwningProcess) } catch { Write-Warning 'Предварительная проверка портов недоступна. Результат запуска будет проверен через агент.' } if ($portOwners.Count -gt 0) { throw "Порты DarwinPC заняты: PID $(($portOwners | Sort-Object -Unique) -join ', '). Проверьте старую версию или другой сеанс Windows. Процессы не завершены." } Write-Host 'Запуск. Если Windows запросит права для настройки брандмауэра, подтвердите запрос.' $agent = Start-Process -FilePath $executable -WindowStyle Hidden -PassThru try { $deadline = [DateTime]::UtcNow.AddSeconds(110) $ready = $false do { if ($agent.HasExited) { throw "DarwinPC завершился при запуске (код $($agent.ExitCode)). Лог: $env:LOCALAPPDATA\Orion\PcAgent\agent.log" } $status = Convert-DarwinStatus (Invoke-DarwinCommand $executable '--status') $ready = Test-DarwinStartup $status $agent.Id $releaseVersion if (-not $ready) { Start-Sleep -Milliseconds 500 } } while (-not $ready -and [DateTime]::UtcNow -lt $deadline) if (-not $ready) { throw 'Начальная настройка не завершена. Проверьте запрос Windows и выполните --diagnose; агент не остановлен.' } if (-not $status.LanListening -and -not $status.BluetoothStarted) { throw "DarwinPC запущен, но оба канала недоступны. LAN: $($status.Lan.Detail) Bluetooth: $($status.Bluetooth.Detail)" } Write-Host "DarwinPC $releaseVersion запущен. Откройте управление на часах." Write-Host "Wi-Fi / LAN: $($status.Lan.Detail)" Write-Host "Bluetooth: $($status.Bluetooth.Detail)" if (-not $status.Firewall -or -not $status.Firewall.RulesValid) { Write-Warning 'Разрешения LAN в брандмауэре не подтверждены. Bluetooth от них не зависит. Выполните --diagnose.' } if ($status.OwnerTrust -ne 'trusted') { Write-Warning 'Сохранённое доверие не включает текущий сертификат персональных часов. Требуется явное подтверждение, данные не сброшены.' } Write-Host 'Для Bluetooth добавьте часы в устройствах Windows. Для LAN это не требуется.' Write-Host "Диагностика: & '$executable' --diagnose | Out-String" Write-Host "Повторный запуск: & '$executable'" } finally { $agent.Dispose() } } Invoke-DarwinInstall }