Private/monster_wu.ps1

# ==============================================================================
# MONSTER SCRIPT ENTERPRISE - WINDOWS UPDATE PAYLOAD (MODULE EDITION)
# Файл: Private\monster_wu.ps1
# Назначение: Управление обновлениями с поддержкой мультиязычной локализации
# ==============================================================================

[CmdletBinding()]
param(
    [switch]$Check,
    [switch]$Install,

    [Parameter(Mandatory = $false)]
    [ValidatePattern('^[a-zA-Z]{2}(-[a-zA-Z]{2,4})?$')]
    [string]$Language
)

# ------------------------------------------------------------------------------
# Автономный fallback для Write-Log
# ------------------------------------------------------------------------------

if (-not (Get-Command -Name Write-Log -ErrorAction SilentlyContinue)) {
    function Write-Log {
        param(
            [Parameter(Mandatory = $true)]
            [string]$Level,

            [Parameter(Mandatory = $true)]
            [string]$Message,

            [string]$Context = 'GENERAL'
        )

        $timestamp = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')

        $color = switch ($Level.ToUpperInvariant()) {
            'SUCCESS'  { 'Green' }
            'WARNING'  { 'Yellow' }
            'ERROR'    { 'Red' }
            'CRITICAL' { 'DarkRed' }
            'VERBOSE'  { 'Magenta' }
            'DEBUG'    { 'DarkGray' }
            default    { 'Cyan' }
        }

        Write-Host `
            "[$timestamp] [$Level] [$Context] $Message" `
            -ForegroundColor $color
    }
}

# ------------------------------------------------------------------------------
# Определение директории скрипта
# ------------------------------------------------------------------------------

$scriptDir = $PSScriptRoot

if (-not $scriptDir -and $MyInvocation.MyCommand.Path) {
    $scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
}

if (-not $scriptDir) {
    $scriptDir = (Get-Location).Path
}

# ------------------------------------------------------------------------------
# Подключение MonsterCore
# ------------------------------------------------------------------------------

$coreModulePath = Join-Path `
    -Path (Split-Path -Parent $scriptDir) `
    -ChildPath 'Private\MonsterCore.psm1'

if (-not (Test-Path -LiteralPath $coreModulePath -PathType Leaf)) {
    $coreModulePath = Join-Path `
        -Path $scriptDir `
        -ChildPath 'MonsterCore.psm1'
}

if (-not (Get-Command -Name Get-MonsterLocalization -ErrorAction SilentlyContinue)) {
    if (Test-Path -LiteralPath $coreModulePath -PathType Leaf) {
        try {
            Import-Module `
                -Name $coreModulePath `
                -Force `
                -ErrorAction Stop
        }
        catch {
            Write-Log `
                -Level 'ERROR' `
                -Message "Не удалось загрузить MonsterCore: $($_.Exception.Message)" `
                -Context 'WU'

            exit 1
        }
    }
}

# ------------------------------------------------------------------------------
# Установка языка
# ------------------------------------------------------------------------------

if (
    $Language -and
    (Get-Command -Name Set-MonsterLanguage -ErrorAction SilentlyContinue)
) {
    Set-MonsterLanguage -Language $Language
}

# ------------------------------------------------------------------------------
# Загрузка локализации
# ------------------------------------------------------------------------------

$msg = @{}

if (Get-Command -Name Get-MonsterLocalization -ErrorAction SilentlyContinue) {
    try {
        $msg = Get-MonsterLocalization `
            -ComponentName 'monster_wu' `
            -Language $Language
    }
    catch {
        Write-Log `
            -Level 'WARNING' `
            -Message "Не удалось загрузить локализацию: $($_.Exception.Message)" `
            -Context 'WU'
    }
}

# ------------------------------------------------------------------------------
# Локализованные сообщения с fallback-текстами
# ------------------------------------------------------------------------------

$txtInit = if ($msg.InitWU) {
    $msg.InitWU
}
else {
    'Инициализация подсистемы Windows Update...'
}

$txtMissingCrit = if ($msg.ModuleMissingCrit) {
    $msg.ModuleMissingCrit
}
else {
    'Модуль PSWindowsUpdate не установлен в системе.'
}

$txtMissingThrow = if ($msg.ModuleMissingThrow) {
    $msg.ModuleMissingThrow
}
else {
    'Модуль PSWindowsUpdate отсутствует.'
}

$txtLoadError = if ($msg.ModuleLoadError) {
    $msg.ModuleLoadError
}
else {
    'Не удалось загрузить модуль PSWindowsUpdate: {0}'
}

$txtSearch = if ($msg.SearchUpdates) {
    $msg.SearchUpdates
}
else {
    'Поиск доступных обновлений Windows...'
}

$txtNoUpdatesLog = if ($msg.NoUpdates) {
    $msg.NoUpdates
}
else {
    'Доступные обновления не обнаружены. Система актуальна.'
}

$txtNoUpdatesHost = if ($msg.OkNoUpdates) {
    $msg.OkNoUpdates
}
else {
    '[OK] Обновления не найдены.'
}

$txtInstallStart = if ($msg.InstallStart) {
    $msg.InstallStart
}
else {
    'Запуск процесса установки обновлений Windows...'
}

$txtInstallDone = if ($msg.InstallSuccess) {
    $msg.InstallSuccess
}
else {
    'Установка обновлений успешно завершена.'
}

$txtInstallHost = if ($msg.OkInstall) {
    $msg.OkInstall
}
else {
    '[OK] Обновления успешно установлены.'
}

$txtNoActionLog = if ($msg.NoActionWarn) {
    $msg.NoActionWarn
}
else {
    'Не указано действие (-Check или -Install).'
}

$txtUsage = if ($msg.UsageInfo) {
    $msg.UsageInfo
}
else {
    'Использование: monster_wu.ps1 [-Check] [-Install] [-Language ru|ua|en]'
}

$txtCritError = if ($msg.CritError) {
    $msg.CritError
}
else {
    'Критическая ошибка в подсистеме Windows Update: {0}'
}

$isVerbose = (
    $PSBoundParameters.ContainsKey('Verbose') -or
    $VerbosePreference -eq 'Continue'
)

Write-Log `
    -Level 'INFO' `
    -Message $txtInit `
    -Context 'WU'

# ------------------------------------------------------------------------------
# Проверка и загрузка PSWindowsUpdate
# ------------------------------------------------------------------------------

try {
    if (-not (Get-Module -ListAvailable -Name 'PSWindowsUpdate')) {
        Write-Log `
            -Level 'CRITICAL' `
            -Message $txtMissingCrit `
            -Context 'WU'

        throw $txtMissingThrow
    }

    if (-not (Get-Module -Name 'PSWindowsUpdate' -ErrorAction SilentlyContinue)) {
        Import-Module `
            -Name 'PSWindowsUpdate' `
            -ErrorAction Stop
    }
}
catch {
    $loadErrorMessage = if ($msg.ModuleLoadError) {
        $msg.ModuleLoadError -f $_.Exception.Message
    }
    else {
        $txtLoadError -f $_.Exception.Message
    }

    Write-Log `
        -Level 'ERROR' `
        -Message $loadErrorMessage `
        -Context 'WU'

    exit 1
}

# ------------------------------------------------------------------------------
# Основная логика Windows Update
# ------------------------------------------------------------------------------

try {
    # --------------------------------------------------------------------------
    # Проверка доступных обновлений
    # --------------------------------------------------------------------------

    if ($Check) {
        Write-Log `
            -Level 'INFO' `
            -Message $txtSearch `
            -Context 'WU'

        $updates = @(
            Get-WindowsUpdate `
                -ErrorAction Stop
        )

        if ($updates.Count -eq 0) {
            Write-Log `
                -Level 'SUCCESS' `
                -Message $txtNoUpdatesLog `
                -Context 'WU'

            Write-Host `
                $txtNoUpdatesHost `
                -ForegroundColor Green
        }
        else {
            $updatesFoundMsg = if ($msg.UpdatesFound) {
                $msg.UpdatesFound -f $updates.Count
            }
            else {
                "Обнаружены доступные обновления ($($updates.Count) шт.)."
            }

            Write-Log `
                -Level 'SUCCESS' `
                -Message $updatesFoundMsg `
                -Context 'WU'

            $headerText = if ($msg.UpdatesHeader) {
                $msg.UpdatesHeader
            }
            else {
                'Доступные обновления:'
            }

            Write-Host `
                "`n$headerText" `
                -ForegroundColor Cyan

            $updates |
                Select-Object `
                    @{
                        Name = 'KB'
                        Expression = {
                            if ($_.KB) {
                                $_.KB
                            }
                            else {
                                'DEFENDER/OTHER'
                            }
                        }
                    },
                    @{
                        Name = 'Size'
                        Expression = {
                            if ($null -ne $_.Size -and $_.Size -gt 0) {
                                '{0} MB' -f [Math]::Round(
                                    ($_.Size / 1MB),
                                    2
                                )
                            }
                            else {
                                'N/A'
                            }
                        }
                    },
                    Title |
                Format-Table -AutoSize
        }

        exit 0
    }

    # --------------------------------------------------------------------------
    # Установка обновлений
    # --------------------------------------------------------------------------

    if ($Install) {
        Write-Log `
            -Level 'INFO' `
            -Message $txtInstallStart `
            -Context 'WU'

        Install-WindowsUpdate `
            -AcceptAll `
            -AutoReboot:$false `
            -Confirm:$false `
            -ErrorAction Stop |
            Out-Null

        Write-Log `
            -Level 'SUCCESS' `
            -Message $txtInstallDone `
            -Context 'WU'

        Write-Host `
            $txtInstallHost `
            -ForegroundColor Green

        exit 0
    }

    # --------------------------------------------------------------------------
    # Отсутствие действия
    # --------------------------------------------------------------------------

    if (-not $Check -and -not $Install) {
        Write-Log `
            -Level 'WARNING' `
            -Message $txtNoActionLog `
            -Context 'WU'

        Write-Host `
            $txtUsage `
            -ForegroundColor Yellow

        exit 1
    }
}
catch {
    $criticalMessage = if ($msg.CritError) {
        $msg.CritError -f $_.Exception.Message
    }
    else {
        $txtCritError -f $_.Exception.Message
    }

    Write-Log `
        -Level 'CRITICAL' `
        -Message $criticalMessage `
        -Context 'WU'

    exit 1
}