Private/task_manager.ps1

# ==============================================================================
# MONSTER SCRIPT ENTERPRISE - TASK MANAGER PAYLOAD (SCHTASKS EDITION)
# Файл: Private\task_manager.ps1
# Назначение: Управление планировщиком с раздельной мультиязычной локализацией
# ==============================================================================

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

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

# ------------------------------------------------------------------------------
# АВТОНОМНЫЙ ФОЛЛБЭК ДЛЯ 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 = 'task_manager',

            [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' }
            default    { 'Cyan' }
        }

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

# ------------------------------------------------------------------------------
# ЗАГРУЗКА CORE-МОДУЛЯ
# ------------------------------------------------------------------------------

$scriptDir = $PSScriptRoot

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

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

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

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

if (-not (Get-Module -Name 'MonsterCore' -ErrorAction SilentlyContinue)) {
    if (Test-Path -Path $coreModulePath -PathType Leaf) {
        Import-Module `
            -Name $coreModulePath `
            -Force `
            -ErrorAction Stop
    }
}

# ------------------------------------------------------------------------------
# УСТАНОВКА ЯЗЫКА И ЗАГРУЗКА ЛОКАЛИЗАЦИИ
# ------------------------------------------------------------------------------

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

$msg = @{}

if (Get-Command -Name Get-MonsterLocalization -ErrorAction SilentlyContinue) {
    # Загружаем словарь интерфейсной части (main) для форматирования в консоли
    $msg = Get-MonsterLocalization `
        -ComponentName 'task_manager' `
        -Language $Language `
        -Category 'main'
}

$isVerbose = (
    $PSBoundParameters['Verbose'] -or
    $VerbosePreference -eq 'Continue'
)

# Вывод стартового сообщения через категорию логов (logs)
Write-Log `
    -Level 'INFO' `
    -Message 'StartMessage' `
    -ComponentName 'task_manager' `
    -Language $Language `
    -Context 'MANAGER'

# ------------------------------------------------------------------------------
# КОНФИГУРАЦИЯ ЗАДАЧ
# ------------------------------------------------------------------------------

$tasksConfig = @(
    @{
        Name        = 'MonsterMaintenanceAuto'
        Description = 'MonsterScript Enterprise - Автоматическое обслуживание системы по расписанию.'
        Action      = 'Invoke-MonsterMaintenance'
        Argument    = '-Auto'
    },
    @{
        Name        = 'MonsterMaintenancePermanent'
        Description = 'MonsterScript Enterprise - Постоянная задача очистки под TrustedInstaller.'
        Action      = 'Invoke-MonsterMaintenance'
        Argument    = '-ExecuteCleanup'
    },
    @{
        Name        = 'MonsterRepairApps'
        Description = 'MonsterScript Enterprise - Восстановление UWP/AppX пакетов.'
        Action      = 'Invoke-MonsterMaintenance'
        Argument    = '-RepairApps'
    }
)

try {
    # --------------------------------------------------------------------------
    # CHECK
    # --------------------------------------------------------------------------

    if ($Check) {
        Write-Log `
            -Level 'INFO' `
            -Message 'CheckStart' `
            -ComponentName 'task_manager' `
            -Language $Language `
            -Context 'MANAGER'

        foreach ($cfg in $tasksConfig) {
            $tName = $cfg.Name

            $queryOutput = & schtasks.exe `
                /query `
                /tn $tName `
                2>&1

            if ($LASTEXITCODE -eq 0) {
                Write-Host `
                    " [OK] Задача найдена: $tName" `
                    -ForegroundColor Green

                Write-Log `
                    -Level 'SUCCESS' `
                    -Message 'TaskFound' `
                    -ComponentName 'task_manager' `
                    -Language $Language `
                    -Arguments @($tName) `
                    -Context 'MANAGER'
            }
            else {
                Write-Host `
                    " [!] Задача НЕ НАЙДЕНА: $tName" `
                    -ForegroundColor Yellow

                Write-Log `
                    -Level 'WARNING' `
                    -Message 'TaskNotFound' `
                    -ComponentName 'task_manager' `
                    -Language $Language `
                    -Arguments @($tName) `
                    -Context 'MANAGER'
            }
        }

        exit 0
    }

    # --------------------------------------------------------------------------
    # INSTALL
    # --------------------------------------------------------------------------

if ($Install) {
        Write-Log `
            -Level 'INFO' `
            -Message 'InstallStart' `
            -ComponentName 'task_manager' `
            -Language $Language `
            -Context 'MANAGER'

        $candidateRoots = @(
            "$env:ProgramFiles\PowerShell\Modules\MonsterScript",
            "$env:ProgramFiles\WindowsPowerShell\Modules\MonsterScript",
            "$env:USERPROFILE\Documents\PowerShell\Modules\MonsterScript",
            "$env:USERPROFILE\Documents\WindowsPowerShell\Modules\MonsterScript"
        ) | Where-Object { Test-Path -Path $_ -PathType Container } | Select-Object -Unique

        foreach ($cfg in $tasksConfig) {
            $tName = $cfg.Name

            try {
                if (-not $candidateRoots -or $candidateRoots.Count -eq 0) {
                    throw 'Каталог модуля MonsterScript не найден ни в одном стандартном пути.'
                }

                $rootsExpr = ($candidateRoots | ForEach-Object { "'$_'" }) -join ','
                $cmdBody = (
                    "`$m=($rootsExpr)|%{{gci `"`$_`\*\*.psd1`" -ea 0}}|sort FullName -desc|select -f 1;" +
                    "if(!`$m){{exit 1}};" +
                    "ipmo `$m.FullName -f;" +
                    "$($cfg.Action) $($cfg.Argument)"
                )

                $commandLine = "powershell.exe -NoP -W Hidden -C `"$cmdBody`""

                if ($commandLine.Length -gt 261) {
                    throw ('Строка /tr ({0} симв.) превышает лимит schtasks.exe в 261 символ.' -f $commandLine.Length)
                }

                $createOutput = & schtasks.exe `
                    /create `
                    /tn $tName `
                    /tr $commandLine `
                    /sc ONSTART `
                    /ru 'NT AUTHORITY\SYSTEM' `
                    /rl HIGHEST `
                    /f `
                    2>&1

                if ($LASTEXITCODE -eq 0) {
                    Write-Log `
                        -Level 'SUCCESS' `
                        -Message 'TaskRegistered' `
                        -ComponentName 'task_manager' `
                        -Language $Language `
                        -Arguments @($tName) `
                        -Context 'MANAGER'

                    Write-Host `
                        "[OK] Зарегистрирована задача: $tName" `
                        -ForegroundColor Green
                }
                else {
                    $errFmt = if ($msg.SchtasksError) {
                        $msg.SchtasksError
                    }
                    else {
                        'schtasks exited with error code {0}. Output: {1}'
                    }

                    throw (
                        $errFmt -f
                        $LASTEXITCODE,
                        ($createOutput -join '; ')
                    )
                }
            }
            catch {
                Write-Log `
                    -Level 'ERROR' `
                    -Message 'TaskRegError' `
                    -ComponentName 'task_manager' `
                    -Language $Language `
                    -Arguments @($tName, $_.Exception.Message) `
                    -Context 'MANAGER'
            }
        }

        exit 0
    }

    # --------------------------------------------------------------------------
    # REMOVE
    # --------------------------------------------------------------------------

    if ($Remove) {
        Write-Log `
            -Level 'INFO' `
            -Message 'RemoveStart' `
            -ComponentName 'task_manager' `
            -Language $Language `
            -Context 'MANAGER'

        foreach ($cfg in $tasksConfig) {
            $tName = $cfg.Name

            try {
                $deleteOutput = & schtasks.exe `
                    /delete `
                    /tn $tName `
                    /f `
                    2>&1

                if ($LASTEXITCODE -eq 0) {
                    Write-Log `
                        -Level 'SUCCESS' `
                        -Message 'TaskRemoved' `
                        -ComponentName 'task_manager' `
                        -Language $Language `
                        -Arguments @($tName) `
                        -Context 'MANAGER'

                    Write-Host `
                        "[OK] Удалена задача: $tName" `
                        -ForegroundColor Green
                }
                else {
                    Write-Log `
                        -Level 'WARNING' `
                        -Message 'TaskRemoveWarn' `
                        -ComponentName 'task_manager' `
                        -Language $Language `
                        -Arguments @($tName) `
                        -Context 'MANAGER'
                }
            }
            catch {
                Write-Log `
                    -Level 'ERROR' `
                    -Message 'TaskRemoveError' `
                    -ComponentName 'task_manager' `
                    -Language $Language `
                    -Arguments @($tName, $_.Exception.Message) `
                    -Context 'MANAGER'
            }
        }

        exit 0
    }

    # --------------------------------------------------------------------------
    # FIX
    # --------------------------------------------------------------------------

    if ($Fix) {
        Write-Log `
            -Level 'INFO' `
            -Message 'FixStart' `
            -ComponentName 'task_manager' `
            -Language $Language `
            -Context 'MANAGER'

        $scriptPath = $MyInvocation.MyCommand.Path

        & $scriptPath `
            -Remove `
            -Language $Language

        & $scriptPath `
            -Install `
            -Language $Language

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

    exit 1
}