Payload/scripts/kaden/update-kaden.ps1

# Write-Host wrapper for KadenUpdateStatus to not trigger PSScriptAnalyzer rule PSAvoidUsingWriteHost
function Write-KadenUpdateStatus {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute(
        'PSAvoidUsingWriteHost', '',
        Justification = 'Operator-facing installer status; not a return value.'
    )]
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$Message,

        [ConsoleColor]$ForegroundColor = 'Gray'
    )

    Write-Host $Message -ForegroundColor $ForegroundColor
}

# 1. Define Module Settings
$moduleName = "Kaden"
$repoName   = "PSGallery"

Write-KadenUpdateStatus -Message "`nChecking for the latest version of '$moduleName' on $repoName..." -ForegroundColor Cyan

# 2. Get the absolute latest version available on the gallery (Stable or Beta)
$galleryModule = Find-Module -Name $moduleName -Repository $repoName -AllVersions -AllowPrerelease |
    Sort-Object { [System.Management.Automation.SemanticVersion]$_.Version } -Descending |
    Select-Object -First 1

if (-not $galleryModule) {
    Write-Error "Could not find module '$moduleName' in the '$repoName' repository ✖"
    return
}

$galleryVersion = $galleryModule.Version
$gallerySemantic = [System.Management.Automation.SemanticVersion]$galleryVersion
Write-KadenUpdateStatus -Message " Most recent version available online: $galleryVersion" -ForegroundColor Yellow

# 3. Check what version (if any) is currently installed.
# Get-InstalledModule without -AllVersions returns a single catalog entry, which can be an older prerelease.
$installedModules = @(Get-InstalledModule -Name $moduleName -AllVersions -ErrorAction SilentlyContinue)
$localModule = $installedModules |
    Sort-Object { [System.Management.Automation.SemanticVersion]$_.Version } -Descending |
    Select-Object -First 1
$localVersion = $localModule.Version

if ($localVersion) {
    Write-KadenUpdateStatus -Message " Current installed version locally : $localVersion ✔" -ForegroundColor Yellow
} else {
    Write-KadenUpdateStatus -Message " Module is not currently installed locally ✖" -ForegroundColor Gray
}

# 4. Determine if an update or fresh install is required
$localSemantic = if ($localVersion) { [System.Management.Automation.SemanticVersion]$localVersion } else { $null }
if (-not $localSemantic -or ($localSemantic -lt $gallerySemantic)) {
    if (-not $localVersion) {
        Write-KadenUpdateStatus -Message "Installing module '$moduleName' ($galleryVersion)..." -ForegroundColor Green
    } else {
        Write-KadenUpdateStatus -Message "Updating module '$moduleName' to version $galleryVersion..." -ForegroundColor Green
    }

    # Perform the installation/update explicitly targeting PSGallery
    Install-Module -Name $moduleName -Repository $repoName -Scope CurrentUser -AllowPrerelease -Force -AllowClobber
} else {
    Write-KadenUpdateStatus -Message "All good, you already have the most recent version ($localVersion) installed" -ForegroundColor Green
}

# 5. Clean up older versions if they exist
Write-KadenUpdateStatus -Message "`nChecking for and removing older versions..." -ForegroundColor Cyan
$allInstalled = @(Get-InstalledModule -Name $moduleName -AllVersions -ErrorAction SilentlyContinue)
$olderInstalled = @($allInstalled | Where-Object {
        ([System.Management.Automation.SemanticVersion]$_.Version) -lt $gallerySemantic
    })

if ($olderInstalled.Count -gt 0) {
    # Uninstall-Module refuses a version that is still imported in this session.
    Remove-Module -Name $moduleName -Force -ErrorAction SilentlyContinue
    foreach ($mod in $olderInstalled) {
        Write-KadenUpdateStatus -Message " Removing older version: $($mod.Version) ✔" -ForegroundColor DarkGray
        Uninstall-Module -Name $moduleName -RequiredVersion $mod.Version -AllowPrerelease -Force
    }
} else {
    Write-KadenUpdateStatus -Message " No old versions to clean up ✔" -ForegroundColor Gray
}

# 6. Force import the module into the active session.
# Import-Module -Force reloads the on-disk module and leaves any other version already imported in this session.
Remove-Module -Name $moduleName -Force -ErrorAction SilentlyContinue
Write-KadenUpdateStatus -Message "`nImporting '$moduleName' into the current session..." -ForegroundColor Cyan
Import-Module -Name $moduleName -Force

# 7. Verify success and display results
$activeModule = @(Get-Module -Name $moduleName)
if ($activeModule.Count -gt 0) {
    Write-KadenUpdateStatus -Message "`nVerification Success ------------------------------------------------------" -ForegroundColor Green
    foreach ($mod in $activeModule) {
        Write-Output " Module Name : $($mod.Name)"
        Write-Output " Active Version : $($mod.Version)"
    }
    Write-KadenUpdateStatus -Message "`nAvailable Commands:" -ForegroundColor Cyan

    # 8. List all commands exported by this module
    <#
    $commands = Get-Command -Module $moduleName
    if ($commands) {
        foreach ($cmd in $commands) {
            Write-Output " - $($cmd.Name)"
        }
    } else {
        Write-KadenUpdateStatus -Message " (No commands are exported by this module)" -ForegroundColor Gray
    }
    #>

    # Manually write out just what is needed to get started
    Write-Output " ⎿ Get-KadenVersion"
    Write-Output " ⎿ Initialize-KadenRepo"
    Write-Output " ⎿ Repair-KadenRepo"
    Write-Output " ⎿ Test-KadenRepo"
    Write-Output " ⎿ Update-KadenRepo"

    # 9. Provide next steps
    Write-KadenUpdateStatus -Message "`n❯ Next Step: Initialize or Update your repository with 'Initialize-KadenRepo' / 'Update-KadenRepo'" -ForegroundColor Yellow
    Write-KadenUpdateStatus -Message " Example:" -ForegroundColor Yellow
    Write-KadenUpdateStatus -Message " Initialize-KadenRepo -Path <path-to-repo> -ProjectId '<repo-name>' -BetaInvitation <passphrase> -Stack <Node|PowerShell|Python|SQL|Polyglot|None>" -ForegroundColor Cyan
    Write-Output "`n› use 'Get-Help <command-name>' for more information"
    Write-Output "`n"
} else {
    Write-Error "Failed to import the module after installation ✖"
}