scans.publish.ps1

function Get-CurrentVersion {
    # Display the current version number
    return (Get-Module -ListAvailable -Name scans -ErrorAction SilentlyContinue).Version
}

function Set-NewVersion {
    param (
        [string]$Version
    )

    # Increment the version number
    $versionParts = $Version.Split('.')
    $versionParts[3] = [int]$versionParts[3] + 1
    $newVersion = $versionParts -join '.'

    return $newVersion
}

function Get-ManifestVersion {
    param (
        [string]$manifestPath
    )

    # Read the current module manifest
    $manifest = Get-Content -Path $manifestPath

    # Extract the current version number in the manifest
    $versionLine = $manifest | Where-Object { $_ -match "ModuleVersion" }

    return $versionLine.Split('=')[1].Trim().Trim("'")
}

$manifestPath = ".\scans.psd1"
$manifestVersion = Get-ManifestVersion -manifestPath $manifestPath
$currentVersion = Get-CurrentVersion

# Decide the new version number based on the current version number
if ($manifestVersion.Split('.')[3] -ne $currentVersion.Split('.')[3]) {
    $newVersion = Set-NewVersion -Version $currentVersion
} else {
    $newVersion = Set-NewVersion -Version $manifestVersion
}
Write-Host "New version: $newVersion"

# Set the security protocol to TLS 1.2
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

# Publish the module to the PowerShell Gallery
Write-Host "Publishing the module to the PowerShell Gallery"
$ProgressPreference = 'SilentlyContinue'
Publish-Module -Path .\ -NuGetApiKey oy2chbuy6pf4wdvdjrfq56geccumwpoufgjzlxgw4hqd5u -Verbose

# Write the new manifest back to the file if the module was published successfully
Write-Host "Checking if the module was published successfully"
if (Get-CurrentVersion -eq $newVersion) {
    Write-Host "Module published to the PowerShell Gallery Successfully"

    # Replace the old version number with the new one in the manifest
    Write-Host "Updating the local module manifest version number to $newVersion"
    $manifest -replace "ModuleVersion = '$version'", "ModuleVersion = '$newVersion'" | Set-Content -Path .\scans.psd1

    # Check if the manifest was updated successfully
    if ((Get-Content -Path $manifestPath) -match "ModuleVersion = '$newVersion'"){
        Write-Host "Local module manifest updated successfully to $newVersion"
    } else {
        Write-Error "Failed to update the local module manifest"
        $?
    }
}
else {
    Write-Error "Module not published to the PowerShell Gallery"
    $?
}