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

        $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) {
    $msg = Get-MonsterLocalization `
        -ComponentName 'task_manager' `
        -Language $Language
}

# ------------------------------------------------------------------------------
# ФОЛЛБЭК-СООБЩЕНИЯ
# ------------------------------------------------------------------------------

$txtStart = if ($msg.StartMessage) {
    $msg.StartMessage
}
else {
    'Старт менеджера планировщика задач...'
}

$txtCheckStart = if ($msg.CheckStart) {
    $msg.CheckStart
}
else {
    'Проверка статуса задач в Планировщике...'
}

$txtInstallStart = if ($msg.InstallStart) {
    $msg.InstallStart
}
else {
    'Регистрация задач в Планировщике Windows...'
}

$txtRemoveStart = if ($msg.RemoveStart) {
    $msg.RemoveStart
}
else {
    'Удаление задач из Планировщика Windows...'
}

$txtFixStart = if ($msg.FixStart) {
    $msg.FixStart
}
else {
    'Запуск процедуры исправления и перерегистрации задач...'
}

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

Write-Log `
    -Level 'INFO' `
    -Message $txtStart `
    -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 $txtCheckStart `
            -Context 'MANAGER'

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

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

            if ($LASTEXITCODE -eq 0) {
                $foundMsg = if ($msg.TaskFound) {
                    $msg.TaskFound -f $tName
                }
                else {
                    "Задача [$tName] присутствует в планировщике."
                }

                Write-Host `
                    " [OK] Задача найдена: $tName" `
                    -ForegroundColor Green

                Write-Log `
                    -Level 'SUCCESS' `
                    -Message $foundMsg `
                    -Context 'MANAGER'
            }
            else {
                $notFoundMsg = if ($msg.TaskNotFound) {
                    $msg.TaskNotFound -f $tName
                }
                else {
                    "Задача [$tName] отсутствует в планировщике."
                }

                Write-Host `
                    " [!] Задача НЕ НАЙДЕНА: $tName" `
                    -ForegroundColor Yellow

                Write-Log `
                    -Level 'WARNING' `
                    -Message $notFoundMsg `
                    -Context 'MANAGER'
            }
        }

        exit 0
    }

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

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

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

            try {
                $commandLine = (
                    'powershell.exe -NoProfile -WindowStyle Hidden -Command ' +
                    'Import-Module MonsterScript; ' +
                    "$($cfg.Action) $($cfg.Argument)"
                )

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

                if ($LASTEXITCODE -eq 0) {
                    $regMsg = if ($msg.TaskRegistered) {
                        $msg.TaskRegistered -f $tName
                    }
                    else {
                        "Задача [$tName] успешно зарегистрирована."
                    }

                    Write-Log `
                        -Level 'SUCCESS' `
                        -Message $regMsg `
                        -Context 'MANAGER'

                    Write-Host `
                        "[OK] Зарегистрирована задача: $tName" `
                        -ForegroundColor Green
                }
                else {
                    $errFmt = if ($msg.SchtasksError) {
                        $msg.SchtasksError
                    }
                    else {
                        'schtasks завершился с кодом ошибки {0}. Вывод: {1}'
                    }

                    throw (
                        $errFmt -f
                        $LASTEXITCODE,
                        ($createOutput -join '; ')
                    )
                }
            }
            catch {
                $errMsg = if ($msg.TaskRegError) {
                    $msg.TaskRegError -f $tName
                }
                else {
                    "Не удалось зарегистрировать задачу [$tName]:"
                }

                Write-Log `
                    -Level 'ERROR' `
                    -Message "$errMsg $($_.Exception.Message)" `
                    -Context 'MANAGER'
            }
        }

        exit 0
    }

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

    if ($Remove) {
        Write-Log `
            -Level 'INFO' `
            -Message $txtRemoveStart `
            -Context 'MANAGER'

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

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

                if ($LASTEXITCODE -eq 0) {
                    $remMsg = if ($msg.TaskRemoved) {
                        $msg.TaskRemoved -f $tName
                    }
                    else {
                        "Задача [$tName] удалена."
                    }

                    Write-Log `
                        -Level 'SUCCESS' `
                        -Message $remMsg `
                        -Context 'MANAGER'

                    Write-Host `
                        "[OK] Удалена задача: $tName" `
                        -ForegroundColor Green
                }
                else {
                    $warnMsg = if ($msg.TaskRemoveWarn) {
                        $msg.TaskRemoveWarn -f $tName
                    }
                    else {
                        "Задача [$tName] не найдена при попытке удаления или уже отсутствует."
                    }

                    Write-Log `
                        -Level 'WARNING' `
                        -Message $warnMsg `
                        -Context 'MANAGER'
                }
            }
            catch {
                $errDelMsg = if ($msg.TaskRemoveError) {
                    $msg.TaskRemoveError -f $tName
                }
                else {
                    "Ошибка при удалении задачи [$tName]:"
                }

                Write-Log `
                    -Level 'ERROR' `
                    -Message "$errDelMsg $($_.Exception.Message)" `
                    -Context 'MANAGER'
            }
        }

        exit 0
    }

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

    if ($Fix) {
        Write-Log `
            -Level 'INFO' `
            -Message $txtFixStart `
            -Context 'MANAGER'

        $scriptPath = $MyInvocation.MyCommand.Path

        & $scriptPath `
            -Remove `
            -Language $Language

        & $scriptPath `
            -Install `
            -Language $Language

        exit 0
    }
}
catch {
    $critMsg = if ($msg.CritError) {
        $msg.CritError
    }
    else {
        'Критическая ошибка в менеджере задач:'
    }

    Write-Log `
        -Level 'CRITICAL' `
        -Message "$critMsg $($_.Exception.Message)" `
        -Context 'MANAGER'

    exit 1
}