[cmdletBinding()]
param()

function Check-WindowsServer2025 {
  $osname = (get-wmiobject Win32_OperatingSystem).Caption
  if ($osname.Contains("Windows Server 2025")) {
     return $true
  } else {
     return $false
  }
}

function Check-AzureLocal23H2 {
  $osname = (get-wmiobject Win32_OperatingSystem).Caption
  $osver = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").DisplayVersion
  if ($osname.Contains("Azure Stack HCI")) {
     if ($osver -eq "23H2") {
       return $true
     } else {
       return $false
     }
  } else {
     return $false
  }
}

function Install-MicrosoftOsConfigModule {
  $osConfigModule = "Microsoft.OSConfig"
  $moduleExists = Get-InstalledModule -Name $osConfigModule -AllVersions -ErrorAction silentlycontinue

  if ($moduleExists) {
    # No installation performed
    return $false
  } else {
    # Install the package providers if not already installed
    Get-PackageProvider -Name PowerShellGet -ForceBootstrap | Out-Null
    Get-PackageProvider -Name NuGet -ForceBootstrap | Out-Null

    Install-Module -Name $osConfigModule -Repository PSGallery -Scope AllUsers -Force
    return $true
  }
}

function Update-MicrosoftOsConfigModule {
  $osConfigModule = "Microsoft.OSConfig"
  $installedModule = Get-InstalledModule -Name $osConfigModule -ErrorAction silentlycontinue

  $latestModule = Find-Module -Name $osConfigModule -Repository PSGallery -ErrorAction silentlycontinue

  if ($installedModule -and $latestModule -and ($latestModule.Version -gt $installedModule.Version)) {
    Uninstall-Module -Name $osConfigModule -AllVersions -Force
    Install-Module -Name $osConfigModule -Scope AllUsers -Repository PSGallery -Force
    return $true
  } else {
    # No update performed
    return $false
  }
}

if (Check-WindowsServer2025) {
  Write-Verbose "Check-WindowsServer2025: Windows Server 2025"
} else {
  if (Check-AzureLocal23H2) {
    Write-Verbose "Check-WindowsServer2025: Azure Local 23H2"
  } else {
    Write-Verbose "Check-WindowsServer2025: Unsupported Operating System"
    return $null
    exit
  }
}

if (!(Install-MicrosoftOsConfigModule)) {
  Write-Verbose "Install-MicrosoftOsConfigModule: OsConfig Module Exist"
  Write-Verbose "Update-MicrosoftOsConfigModule: OsConfig Module Try to update"
  if (Update-MicrosoftOsConfigModule) {
    Write-Verbose "Update-MicrosoftOsConfigModule: OsConfig Module updated"
  } else {
    Write-Verbose "Update-MicrosoftOsConfigModule: OsConfig Module latest"
  }
} else {
  Write-Verbose "Install-MicrosoftOsConfigModule: OsConfig Module Installed"
}
$installedmodule = (Get-Module -ListAvailable -Name Microsoft.OSConfig)
Write-Verbose $installedmodule

return 0

