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',

            [string]$ComponentName = 'monster_wu',

            [string]$Language = '',

            [object[]]$Arguments
        )

        $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 'CoreLoadError' `
                -ComponentName 'monster_wu' `
                -Language $Language `
                -Arguments @($_.Exception.Message) `
                -Context 'WU'

            exit 1
        }
    }
}

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

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

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

# Инициализация подсистемы (логирование)
Write-Log `
    -Level 'INFO' `
    -Message 'InitWU' `
    -ComponentName 'monster_wu' `
    -Language $Language `
    -Context 'WU'

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

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

        throw 'PSWindowsUpdate missing'
    }

    if (-not (Get-Module -Name 'PSWindowsUpdate' -ErrorAction SilentlyContinue)) {
        Import-Module `
            -Name 'PSWindowsUpdate' `
            -ErrorAction Stop
    }
}
catch {
    Write-Log `
        -Level 'ERROR' `
        -Message 'ModuleLoadError' `
        -ComponentName 'monster_wu' `
        -Language $Language `
        -Arguments @($_.Exception.Message) `
        -Context 'WU'

    exit 1
}

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

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

    if ($Check) {
        Write-Log `
            -Level 'INFO' `
            -Message 'SearchUpdates' `
            -ComponentName 'monster_wu' `
            -Language $Language `
            -Context 'WU'

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

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

            # Консольный вывод через Get-MonsterLocalization (категория main)
            $mainLoc = Get-MonsterLocalization -ComponentName 'monster_wu' -Language $Language -Category 'main'
            $txtOkNoUpdates = if ($mainLoc.OkNoUpdates) { $mainLoc.OkNoUpdates } else { '[OK] Обновления не найдены.' }

            Write-Host $txtOkNoUpdates -ForegroundColor Green
        }
        else {
            Write-Log `
                -Level 'SUCCESS' `
                -Message 'UpdatesFound' `
                -ComponentName 'monster_wu' `
                -Language $Language `
                -Arguments @($updates.Count) `
                -Context 'WU'

            $mainLoc = Get-MonsterLocalization -ComponentName 'monster_wu' -Language $Language -Category 'main'
            $headerText = if ($mainLoc.UpdatesHeader) { $mainLoc.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 'InstallStart' `
            -ComponentName 'monster_wu' `
            -Language $Language `
            -Context 'WU'

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

        Write-Log `
            -Level 'SUCCESS' `
            -Message 'InstallSuccess' `
            -ComponentName 'monster_wu' `
            -Language $Language `
            -Context 'WU'

        $mainLoc = Get-MonsterLocalization -ComponentName 'monster_wu' -Language $Language -Category 'main'
        $txtOkInstall = if ($mainLoc.OkInstall) { $mainLoc.OkInstall } else { '[OK] Обновления успешно установлены.' }

        Write-Host $txtOkInstall -ForegroundColor Green

        exit 0
    }

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

    if (-not $Check -and -not $Install) {
        Write-Log `
            -Level 'WARNING' `
            -Message 'NoActionWarn' `
            -ComponentName 'monster_wu' `
            -Language $Language `
            -Context 'WU'

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

        Write-Host $txtUsage -ForegroundColor Yellow

        exit 1
    }
}
catch {
    Write-Log `
        -Level 'CRITICAL' `
        -Message 'CritError' `
        -ComponentName 'monster_wu' `
        -Language $Language `
        -Arguments @($_.Exception.Message) `
        -Context 'WU'

    exit 1
}