functions/apphandling/Install-NavApps.ps1

function Install-NavApps {
    [CmdletBinding()]
    param (
        [string]$AppsPath,
        [string]$ServerInstance,
        [string]$Tenant = 'default',
        [switch]$TenantOnly
    )
    
    begin {
        Import-Module "$Env:Programfiles\PowerShellTools\pst.psm1"
    }
    
    process {
            # Get all .app files in the directory and subdirectories
            $appFiles = Get-ChildItem -Path $AppsPath -Recurse -Filter *.app

            if ($appFiles.Length -eq 0)
            {
                Write-HostX "No apps found in path: $($AppsPath)"
            }

            # Create a hashtable to store the latest version of each app
            $latestApps = @{}
            $latestAppPaths = @{}

            foreach ($appFile in $appFiles) {
                # Get the app info
                $appInfo = Get-NAVAppInfo -Path $appFile.FullName
                
                # Check if the app is already in the hashtable
                if ($latestApps.ContainsKey($appInfo.AppId)) {
                    # Compare versions and update if the current app is newer
                    if ([version]$appInfo.Version -gt [version]$latestApps[$appInfo.AppId].Version) {
                        $latestApps[$appInfo.AppId] = $appInfo
                        $latestAppPaths[$appInfo.AppId] = $appFile.FullName
                    }
                } else {
                    # Add the app to the hashtable
                    $latestApps[$appInfo.AppId] = $appInfo
                    $latestAppPaths[$appInfo.AppId] = $appFile.FullName
                }
            }

            # Install the latest version of each app
            foreach ($app in $latestApps.Values) {
                $appPath = $latestAppPaths[$app.AppId]
                Write-Host "Installing app: $($app.Name) version $($app.Version)"
                # Install the app
                if (-not $TenantOnly)
                {
                    Publish-NAVApp -ServerInstance $ServerInstance -Path $appPath -SkipVerification
                    Sync-NAVApp -ServerInstance $ServerInstance -Name $app.Name
                    Install-NAVApp -ServerInstance $ServerInstance -Name $app.Name
                }
                else {
                    Publish-NAVApp -ServerInstance $ServerInstance -Tenant $Tenant -Path $appPath -SkipVerification # really teanant or just sync?
                    Sync-NAVApp -ServerInstance $ServerInstance -Tenant $Tenant -Name $app.Name
                    Install-NAVApp -ServerInstance $ServerInstance -Tenant $Tenant -Name $app.Name
                }
            }
    }
    
    end {
        
    }
}
#Export-ModuleMember Install-NavApps