#######
Write-Verbose -Message "Determine if ITD_PwshGallery is registered" -Verbose
If(Get-PSRepository -Name ITD_PwshGallery -ErrorAction SilentlyContinue){
    Write-Verbose -Message "ITD_PwshGallery found." -Verbose
} Else {
    $RegisterPSRepositoryParams = @{
        Name = 'ITD_PwshGallery';
        InstallationPolicy = 'Trusted';
        SourceLocation = 'https://powershell.nd.gov/ITD_PwshGallery/nuget/';
        PublishLocation = 'https://powershell.nd.gov/ITD_PwshGallery/nuget/';
        ScriptSourceLocation = 'https://powershell.nd.gov/ITD_PwshGallery/nuget/';
        ScriptPublishLocation = 'https://powershell.nd.gov/ITD_PwshGallery/nuget/';
    }
    Register-PSRepository @RegisterPSRepositoryParams
}

Write-Verbose -Message "Retrieve list of all available modules and versions"
$ITDModules = Find-Module -Name "ITD.*" -Repository ITD_PwshGallery


Write-Verbose -Message "Compare local module versions to repository versions, and update if needed"
ForEach($ITDModule in $ITDModules){
    $VersionsAvailable = $null
    $MostRecentVersion = $null
    $RepoVersion = $null

    $VersionsAvailable = Get-Module -Name $ITDModule.name -ListAvailable
    $MostRecentVersion = $VersionsAvailable | Sort-Object Version -Descending | Select -First 1
    $RepoVersion = $ITDModule.Version

    If($null -eq $MostRecentVersion) {
        Write-Verbose -Message ($ITDModule.Name + " was not found locally, installing module now.") -Verbose
        Install-Module -Name $ITDModule.Name -Scope AllUsers -Repository ITD_PwshGallery
    } Else {
        Write-Verbose -Message ($ITDModule.Name + " was found locally, comparing versions and updating if needed..") -Verbose
        Write-Host -Message ($ITDModule.Name)
        Write-Host -Message ("Local version is    " + $MostRecentVersion.Version)
        Write-Host -Message ("The Repo version is " + $RepoVersion)
        Write-Host -Message ("")
        Update-Module -Name $ITDModule.Name -Scope AllUsers
    }   
}