Marli-Update.ps1

#region ===== Hilfsfunktionen (privat, werden NICHT exportiert) =====

# Prüft, ob die PowerShell als Administrator läuft
function Test-MarliAdmin {
    $id = [Security.Principal.WindowsIdentity]::GetCurrent()
    (New-Object Security.Principal.WindowsPrincipal $id).IsInRole(
        [Security.Principal.WindowsBuiltInRole]::Administrator)
}

# Schreibt die Kopfzeile
function Show-MarliHeader {
    param([string]$Version)
    Clear-Host
    Write-Host "Marlis Updater - Version $Version" -ForegroundColor Cyan
    Write-Host '---------------------------------'
    Write-Host ''
}

# Führt einen Vorbereitungs-Schritt aus und zeigt [ok] / [skip] / [error]
# Gibt $true (geklappt) oder $false (Fehler) zurück
function Invoke-MarliStep {
    param(
        [string]$Text,
        [scriptblock]$Action
    )
    Write-Host (' {0,-38}' -f $Text) -NoNewline
    try {
        $result = & $Action | Select-Object -Last 1
        if ($result -eq 'Skip') { Write-Host '[present]' -ForegroundColor DarkGray }
        else                    { Write-Host '[ok]'      -ForegroundColor Green }
        return $true
    }
    catch {
        Write-Host '[error]' -ForegroundColor Red
        Write-Host " $($_.Exception.Message)" -ForegroundColor Red
        return $false
    }
}

# NuGet-Provider (wird für Install-Module / Install-Script gebraucht)
function Install-MarliNuGet {
    $nuget = Get-PackageProvider -ListAvailable -Name NuGet -ErrorAction SilentlyContinue |
             Where-Object { $_.Version -ge [version]'2.8.5.201' }
    if ($nuget) { return 'Skip' }

    Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Scope AllUsers -Force -ErrorAction Stop | Out-Null
}

# Winget - nur installieren, wenn es fehlt
function Install-MarliWinget {
    if (Get-Command winget.exe -ErrorAction SilentlyContinue) { return 'Skip' }

    # Offizielles Installer-Skript von asheroto aus der PSGallery holen
    Install-Script -Name winget-install -Scope AllUsers -Force -ErrorAction Stop
    $script = Join-Path (Get-InstalledScript -Name winget-install).InstalledLocation 'winget-install.ps1'

    # In eigenem Prozess starten (das Skript beendet sich mit "exit")
    Start-Process powershell.exe -ArgumentList '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', "`"$script`"", '-Force' `
                  -Wait -WindowStyle Hidden

    # PATH neu laden, damit winget sofort gefunden wird
    $env:Path = [Environment]::GetEnvironmentVariable('Path', 'Machine') + ';' +
                [Environment]::GetEnvironmentVariable('Path', 'User')

    if (-not (Get-Command winget.exe -ErrorAction SilentlyContinue)) {
        throw 'winget could not be installed.'
    }
}

# PSWindowsUpdate - nur installieren, wenn es fehlt
function Install-MarliPSWindowsUpdate {
    $result = $null
    if (Get-Module -ListAvailable -Name PSWindowsUpdate) {
        $result = 'Skip'
    }
    else {
        Install-Module -Name PSWindowsUpdate -Scope AllUsers -Force -ErrorAction Stop
    }
    Import-Module PSWindowsUpdate -ErrorAction Stop
    return $result
}

# Software per winget aktualisieren
function Update-MarliSoftware {
    Write-Host ''
    Write-Host 'Checking software updates (winget)...' -ForegroundColor Yellow
    winget.exe upgrade --all --silent --accept-source-agreements --accept-package-agreements
    if ($LASTEXITCODE -eq 0) { Write-Host 'Software: done' -ForegroundColor Green }
    else                     { Write-Warning "winget finished with exit code $LASTEXITCODE (some updates may have failed)." }
}

# Windows per PSWindowsUpdate aktualisieren
function Update-MarliWindows {
    Write-Host ''
    Write-Host 'Checking Windows updates...' -ForegroundColor Yellow
    try {
        Get-WindowsUpdate -AcceptAll -Install -IgnoreReboot -ErrorAction Stop | Out-Host
        Write-Host 'Windows: done' -ForegroundColor Green

        if (Get-WURebootStatus -Silent) {
            Write-Warning 'A restart is required to finish the updates.'
            $answer = Read-Host 'Restart now? (Y/N)'
            if ($answer -match '^[YyJj]') { Restart-Computer -Force }
        }
    }
    catch {
        Write-Host "Windows update failed: $($_.Exception.Message)" -ForegroundColor Red
    }
}

# Menü anzeigen und gültige Auswahl zurückgeben
function Read-MarliChoice {
    param([string]$Version)
    Show-MarliHeader -Version $Version
    $items = [ordered]@{
        '1' = 'Update my Software'
        '2' = 'Update my Windows'
        '3' = 'Update both'
        '0' = 'Exit'
    }
    foreach ($key in $items.Keys) {
        Write-Host '[' -NoNewline
        Write-Host $key -NoNewline -ForegroundColor Green
        Write-Host ']----[ ' -NoNewline
        Write-Host $items[$key] -ForegroundColor Yellow
    }
    Write-Host ''
    do {
        $choice = (Read-Host 'Select and press Enter').Trim()
    } until ($items.Contains($choice))
    return $choice
}

#endregion

#region ===== Öffentliche Funktion =====

function Update-MarliSystem {
    <#
    .SYNOPSIS
        Aktualisiert installierte Software (winget) und Windows (PSWindowsUpdate).
    .PARAMETER Mode
        Menu = Menü anzeigen (Standard)
        Software = nur Software
        Windows = nur Windows
        All = beides, ohne Menü
    .EXAMPLE
        Marli-Update
    .EXAMPLE
        Update-MarliSystem -Mode All
    #>

    [CmdletBinding()]
    param(
        [ValidateSet('Menu', 'Software', 'Windows', 'All')]
        [string]$Mode = 'Menu'
    )

    # 1) Admin-Rechte prüfen - bei Bedarf als Admin neu starten
    if (-not (Test-MarliAdmin)) {
        Write-Warning 'This command needs administrator rights.'
        $answer = Read-Host 'Restart PowerShell as administrator? (Y/N)'
        if ($answer -match '^[YyJj]') {
            Start-Process powershell.exe -Verb RunAs -ArgumentList '-NoExit', '-Command', "Update-MarliSystem -Mode $Mode"
        }
        return
    }

    # Version direkt aus dem Manifest (.psd1) - nur noch an EINER Stelle pflegen
    $version = $MyInvocation.MyCommand.Module.Version

    $oldProgress = $ProgressPreference
    $ProgressPreference = 'SilentlyContinue'
    try {
        # 2) Vorbereitung
        Show-MarliHeader -Version $version
        Write-Host 'Preparation'
        $nugetOk  = Invoke-MarliStep 'Check / install NuGet'           { Install-MarliNuGet }
        $wingetOk = Invoke-MarliStep 'Check / install winget'          { Install-MarliWinget }
        $wuOk     = Invoke-MarliStep 'Check / install PSWindowsUpdate' { Install-MarliPSWindowsUpdate }
        $null = $nugetOk   # nur Info, winget/PSWindowsUpdate prüfen selbst

        if ($Mode -eq 'Menu') { Start-Sleep -Seconds 1 }

        # 3) Ausführen
        do {
            $choice = switch ($Mode) {
                'Software' { '1' }
                'Windows'  { '2' }
                'All'      { '3' }
                default    { Read-MarliChoice -Version $version }
            }

            if ($choice -in '1', '3') {
                if ($wingetOk) { Update-MarliSoftware }
                else { Write-Host 'Skipped software update: winget is missing.' -ForegroundColor Red }
            }
            if ($choice -in '2', '3') {
                if ($wuOk) { Update-MarliWindows }
                else { Write-Host 'Skipped Windows update: PSWindowsUpdate is missing.' -ForegroundColor Red }
            }

            if ($Mode -eq 'Menu' -and $choice -ne '0') {
                Write-Host ''
                Read-Host 'Press Enter to return to the menu' | Out-Null
            }
        } while ($Mode -eq 'Menu' -and $choice -ne '0')
    }
    finally {
        $ProgressPreference = $oldProgress
    }
}

# Alter Name bleibt als Alias -> "Marli-Update" funktioniert weiter
Set-Alias -Name Marli-Update -Value Update-MarliSystem
Export-ModuleMember -Function Update-MarliSystem -Alias Marli-Update

#endregion