Includes/PwSh.Fw.Build.RedHat.psm1

<#
.SYNOPSIS
Convert a generic hashtable into useful RPM specfile metadata
 
.DESCRIPTION
Extract from an object useful properties to use as RPM spec file tags.
Debian specific attributes have no RPM equivalent and are dropped (Essential, Priority,
Installed-Size, Breaks, Pre-Depends...). 'Replaces' maps to 'Obsoletes'.
 
.PARAMETER Metadata
object filled with various properties
 
.EXAMPLE
$project = gc ./project.yml -raw | ConvertFrom-yaml
$project | ConvertTo-RPMSpecFileSettings
 
This example will convert a project definition file into a useable hashtable to inject into Out-RPMSpecFile
 
.NOTES
RPM splits versioning into Version + Release. Release is the build number, or
0.1.pre<build> for prereleases (pre releases sort before the final release).
 
.LINK
https://rpm-software-management.github.io/rpm/manual/spec.html
https://www.redhat.com/sysadmin/create-rpm-package
#>

function ConvertTo-RPMSpecFileSettings {
    [CmdletBinding()][OutputType([hashtable])]
    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification="This cmdlet converts a hashtable into settings, not into a single setting.")]
    Param (
        [Parameter(Mandatory = $true, ValueFromPipeLine = $true)][object]$Metadata
    )
    Begin {
    }

    Process {
        $SpecFields = @{}
        if ($Metadata) {
            if ($Metadata.Name) { $SpecFields.Name = $Metadata.Name }
            if ($Metadata.Package) { $SpecFields.Name = $Metadata.Package }
            # override package name with optional PackageName attribute
            if ($Metadata.PackageName) { $SpecFields.Name = $Metadata.PackageName }
            # rpm package names are lowercase
            if ($SpecFields.Name) { $SpecFields.Name = $SpecFields.Name.ToLower() }
            if ($Metadata.Version) { $SpecFields.Version = [string]$Metadata.Version }
            # detect prerelease : Get-PwShProject sets IsPrerelease (bool) and PreRelease ("-preNN")
            $isPrerelease = $false
            if ($Metadata.PSObject.Properties.Name -contains 'IsPrerelease') { $isPrerelease = [bool]$Metadata.IsPrerelease }
            if (![string]::IsNullOrEmpty($Metadata.PreRelease)) { $isPrerelease = $true }
            $build = 1
            if ($null -ne $Metadata.Build -and "$($Metadata.Build)" -ne '') {
                [int]$parsedBuild = 0
                if ([int]::TryParse("$($Metadata.Build)", [ref]$parsedBuild)) { $build = $parsedBuild }
            }
            if ($isPrerelease) {
                $SpecFields.Release = "0.1.pre$build"
            } else {
                $SpecFields.Release = "$build"
            }
            if ($Metadata.Description) {
                # Summary must be a single line
                $SpecFields.Summary = (($Metadata.Description -split "`n")[0]).Trim()
            }
            if (-not $SpecFields.Summary) { $SpecFields.Summary = $SpecFields.Name }
            if ($Metadata.Description) { $SpecFields.Description = $Metadata.Description }
            # SPDX short form expected, set 'license:' in project.yml (mit, gpl-3.0, apache-2.0, ...)
            if ($Metadata.License) { $SpecFields.License = $Metadata.License }
            if (-not $SpecFields.License) { $SpecFields.License = "UNKNOWN" }
            if ($Metadata.ProjectUri) { $SpecFields.URL = $Metadata.ProjectUri }
            if ($Metadata.ProjectUrl) { $SpecFields.URL = $Metadata.ProjectUrl }
            if ($Metadata.Authors) { $SpecFields.Packager = $Metadata.Authors[0] }
            if ($Metadata.Author) { $SpecFields.Packager = $Metadata.Author }
            if ($Metadata.owner) { $SpecFields.Packager = $Metadata.owner }
            if ($Metadata.Maintainer) { $SpecFields.Packager = $Metadata.Maintainer }
            # debian Section maps to rpm Group
            if ($Metadata.Section) { $SpecFields.Group = $Metadata.Section }
            # map project architecture to rpm BuildArch ('all' becomes 'noarch')
            $arch = $null
            if ($Metadata.Arch) { $arch = $Metadata.Arch }
            if ($Metadata.Architecture) { $arch = $Metadata.Architecture }
            if ($Metadata.ProcessorArchitecture) { $arch = $Metadata.ProcessorArchitecture }
            if ($arch) {
                switch ($arch.ToString().ToLower()) {
                    { $_ -in @('all', 'any', 'noarch') } { $SpecFields.'BuildArch' = 'noarch' }
                    { $_ -in @('x64', 'amd64', 'x86_64') } { $SpecFields.'BuildArch' = 'x86_64' }
                    { $_ -in @('arm64', 'aarch64') } { $SpecFields.'BuildArch' = 'aarch64' }
                    default { $SpecFields.'BuildArch' = $arch.ToString() }
                }
            }
            if (-not $SpecFields.'BuildArch') { $SpecFields.'BuildArch' = 'noarch' }
            if ($Metadata.Depends) { $SpecFields.Requires = @($Metadata.Depends) }
            if ($Metadata.Provides) { $SpecFields.Provides = @($Metadata.Provides) }
            if ($Metadata.Conflicts) { $SpecFields.Conflicts = @($Metadata.Conflicts) }
            # debian 'Replaces' maps to rpm 'Obsoletes'
            if ($Metadata.Replaces) { $SpecFields.Obsoletes = @($Metadata.Replaces) }
        }

        return $SpecFields
    }

    End {
    }
}

<#
.SYNOPSIS
Write a RPM spec file
 
.DESCRIPTION
Output a fully-formatted RPM spec file based on build configuration.
The spec is rendered from a mustache template : every project.yml attribute is
available as a lowercase variable, derived spec fields (name, version, release,
summary, license, url, arch...) override them, and multi-line tag blocks
(requires, provides, conflicts, obsoletes, description, changelog) are
preformatted. Users can provide their own template to add any block they need
(%pre, %post, custom %files, ...).
 
.PARAMETER Metadata
The project's properties
 
.PARAMETER Destination
Directory in which to put the resulting spec file
 
.PARAMETER Template
Optional path to a mustache spec template. Defaults to the built-in Assets/rpm.spec.mustache
 
.PARAMETER PassThru
Use this switch to output the generated spec file content instead of its path
 
.OUTPUTS
Full path to spec file
 
.OUTPUTS
spec file content
 
.EXAMPLE
$project = Get-PwShProject
$project | Out-RPMSpecFile -Destination /tmp/RPM/
 
This example uses a project object and outputs a well-formatted RPM spec file.
The output of this example is "/tmp/RPM/$($project.name).spec"
 
.NOTES
    2023.05 - 1st version
    2026.12 - real spec generation from mustache template
 
.LINK
https://rpm-software-management.github.io/rpm/manual/spec.html
https://www.redhat.com/sysadmin/create-rpm-package
#>

function Out-RPMSpecFile {
    [CmdletBinding()][OutputType([String])]
    Param (
        [Parameter(Mandatory = $true, ValueFromPipeLine = $true)][object]$Metadata,
        [Parameter(Mandatory = $false, ValueFromPipeLine = $false)][string]$Destination,
        [Parameter(Mandatory = $false, ValueFromPipeLine = $false)][string]$Template,
        [switch]$PassThru
    )
    Begin {
        Write-EnterFunction
        if ($Destination) {
            if (!(Test-DirExist $Destination)) { $null = New-Item $Destination -Force -ItemType Directory }
        }
    }

    Process {
        $SpecFields = ConvertTo-RPMSpecFileSettings -Metadata $Metadata
        # template context : every raw project value (lowercase), overridden by derived spec fields
        $Context = @{}
        if ($Metadata -is [System.Collections.IDictionary]) {
            foreach ($k in $Metadata.Keys) { $Context["$k".ToLower()] = $Metadata[$k] }
        } else {
            foreach ($p in $Metadata.PSObject.Properties) { $Context[$p.Name.ToLower()] = $p.Value }
        }
        foreach ($k in $SpecFields.Keys) { $Context[$k.ToLower()] = $SpecFields[$k] }
        # short alias for templates
        $Context['arch'] = $SpecFields.'BuildArch'
        # preformatted multi-line tag blocks (rendered as-is, empty when not set)
        # note : guard each one, piping $null to ForEach-Object would emit one empty "Tag: " line
        $Context['requires'] = if ($SpecFields.Requires) { ($SpecFields.Requires | ForEach-Object { "Requires: $_" }) -join "`n" } else { '' }
        $Context['provides'] = if ($SpecFields.Provides) { ($SpecFields.Provides | ForEach-Object { "Provides: $_" }) -join "`n" } else { '' }
        $Context['conflicts'] = if ($SpecFields.Conflicts) { ($SpecFields.Conflicts | ForEach-Object { "Conflicts: $_" }) -join "`n" } else { '' }
        $Context['obsoletes'] = if ($SpecFields.Obsoletes) { ($SpecFields.Obsoletes | ForEach-Object { "Obsoletes: $_" }) -join "`n" } else { '' }
        $Context['source0'] = "$($SpecFields.Name)-$($SpecFields.Version).tar.gz"
        # optional single-line tags, preformatted (empty line when not set)
        if ($SpecFields.URL) { $Context['urltag'] = "URL: $($SpecFields.URL)" } else { $Context['urltag'] = '' }
        if ($SpecFields.Group) { $Context['grouptag'] = "Group: $($SpecFields.Group)" } else { $Context['grouptag'] = '' }
        if ($SpecFields.Packager) { $Context['packagertag'] = "Packager: $($SpecFields.Packager)" } else { $Context['packagertag'] = '' }
        # %changelog block : header line + latest released changelog bullets
        $changelogLines = @()
        $packager = $SpecFields.Packager
        if ([string]::IsNullOrEmpty($packager)) { $packager = 'unknown' }
        $changelogDate = (Get-Date).ToString('ddd MMM dd yyyy', [System.Globalization.CultureInfo]::InvariantCulture)
        $changelogLines += "* $changelogDate $packager - $($SpecFields.Name)-$($SpecFields.Release)"
        $changelogPath = $null
        if ($Metadata -is [System.Collections.IDictionary]) {
            if ($Metadata.ContainsKey('Root')) { $changelogPath = Join-Path $Metadata.Root 'CHANGELOG.md' }
        } elseif ($Metadata.PSObject.Properties.Name -contains 'Root') {
            $changelogPath = Join-Path $Metadata.Root 'CHANGELOG.md'
        }
        if ($changelogPath -and (Test-Path $changelogPath) -and (Get-Command -Name Get-PwShProjectChangelog -ErrorAction SilentlyContinue)) {
            $cl = Get-PwShProjectChangelog -Path $changelogPath
            if ($cl) {
                $body = $cl.Values | Where-Object { $_ -notmatch 'unreleased' } | Select-Object -First 1
                if ($body) {
                    foreach ($line in ($body -split "`n" | ForEach-Object { $_.Trim() } | Where-Object { $_ -like '-*' })) {
                        $changelogLines += $line
                    }
                }
            }
        }
        if ($changelogLines.Count -le 1) { $changelogLines += '- initial package' }
        $Context['changelog'] = $changelogLines -join "`n"

        if ([string]::IsNullOrEmpty($Template)) {
            # resolve the built-in template relative to this file (works standalone or as nested module)
            $Template = Join-Path (Split-Path $PSScriptRoot -Parent) "Assets/rpm.spec.mustache"
        }
        if (!(Test-Path $Template)) { Write-Fatal "Spec template '$Template' not found." }
        $rendered = ConvertFrom-MustacheTemplate -Template (Get-Content -Raw $Template) -Values $Context
        $Filename = "$Destination/$($SpecFields.Name).spec"
        $rendered | Out-File -Path $Filename -Encoding utf8

        if ($PassThru) {
            return $rendered
        } else {
            return (Resolve-Path -Path $Filename).Path
        }
    }

    End {
        Write-LeaveFunction
    }
}

<#
.SYNOPSIS
Build the project to a red hat (RPM) package
 
.DESCRIPTION
Build the project to a full featured RPM package.
The payload is staged under /opt/<name>/ and packaged with rpmbuild.
If a RedHatFolder is provided, its files are added to the payload (*.mustache
files are rendered with the project values) and a *.spec(.mustache) template
found there is used. A fully custom spec template can be forced with -SpecFile.
 
.EXAMPLE
New-RedHatBuild -Project (Get-PwShProject)
 
.NOTES
The resulting package will be named after project's data :
`<name>-<version>-<release>.<arch>.rpm`
#>

function New-RedHatBuild {
    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Low', DefaultParameterSetName = 'PROJECT')]
    [OutputType([Boolean], [String])]
    Param (
        # The project object as returned by Get-PwShProject
        [Parameter(Mandatory = $true, ValueFromPipeLine = $true)][hashtable]$Project,

        # An optional RedHat folder where the RPM spec template and extra payload files are stored.
        # *.mustache files are rendered with the project values.
        [Alias('Configuration')]
        [Parameter(Mandatory = $false, ValueFromPipeLine = $false)][string]$RedHatFolder = "./build/RedHat",

        # An optional custom spec template (mustache). If not given, a *.spec(.mustache) found in
        # the RedHatFolder is used, else the built-in default template.
        [Parameter(Mandatory = $false, ValueFromPipeLine = $false)][string]$SpecFile,

        # The source folder of your project. Files and directory structure will be kept as-is under /opt/<name>/
        [Parameter(Mandatory = $false, ValueFromPipeLine = $false)][string]$Source = "./src",

        # Destination folder to create resulting package
        [Parameter(Mandatory = $false, ValueFromPipeLine = $false)][string]$Destination = "./releases",

        # Override output package filename.
        # It defaults to <name>-<version>-<release>.<arch>.rpm
        [Parameter(Mandatory = $false, ValueFromPipeLine = $false)][string]$OutputFileName,

        # Force/override/overwrite things
        [switch]$Force
    )
    Begin {
        Write-EnterFunction
        if (!(Test-DirExist $Destination)) {
            $null = New-Item -Path $Destination -ItemType Directory -Confirm:$false -Force:$Force
        }
    }

    Process {
        $SpecFields = $Project | ConvertTo-RPMSpecFileSettings
        $Name = $SpecFields.Name
        if ([string]::IsNullOrEmpty($OutputFileName)) {
            $Filename = "$($Name)-$($SpecFields.Version)-$($SpecFields.Release).$($SpecFields.'BuildArch').rpm"
        } else {
            $Filename = $OutputFileName
        }
        if ($PSCmdlet.ShouldProcess("$Destination/$Filename", "Create RPM package")) {
            if (!(Get-Command -Name rpmbuild -ErrorAction SilentlyContinue)) { Write-Fatal "rpmbuild command not found in system. Try to install the rpm-build package." }
            # temporary _topdir tree
            $TopDir = Join-Path ([System.IO.Path]::GetTempPath()) "rpm-$Name-$(Get-Random)"
            foreach ($d in @('SPECS', 'SOURCES', 'BUILD', 'RPMS', 'SRPMS')) {
                $null = New-Item -Path "$TopDir/$d" -ItemType Directory -Force
            }
            # stage the payload : <name>-<version>/ must be the tarball's top-level directory so %setup -q works
            $PayloadRoot = Join-Path $TopDir "payload-root"
            $PayloadDir = Join-Path $PayloadRoot "$Name-$($SpecFields.Version)"
            $null = New-Item -Path $PayloadDir -ItemType Directory -Force
            if (Test-DirExist $Source) {
                Copy-Item "$Source/*" -Destination $PayloadDir -Recurse -Force:$Force
            } else {
                Write-Warning "Source folder '$Source' not found, building an empty payload."
            }
            # RedHatFolder : extra payload files + optional spec template
            # its content is copied at the payload root (so it lands in /opt/<name>/), mirroring how
            # New-DebianBuild renders *.mustache from the DEBIAN folder
            $Template = $SpecFile
            if (Test-DirExist $RedHatFolder) {
                $RedHatFolder = (Resolve-Path $RedHatFolder).Path
                Copy-Item "$RedHatFolder/*" -Destination $PayloadDir -Recurse -Force:$Force -Exclude "*.mustache", "*.spec", "*.spec.mustache"
                # render payload templates, but not spec templates (*.spec(.mustache) are not payload content)
                Get-ChildItem $RedHatFolder -Recurse -Filter "*.mustache" | Where-Object { $_.Name -notmatch '\.spec\.mustache$' } | ForEach-Object {
                    $item = $_
                    $destFilePath = $item.DirectoryName -replace [regex]::Escape($RedHatFolder), $PayloadDir
                    $destFile = "$destFilePath/$($item.Basename)"
                    $null = New-Item -Path (Split-Path $destFile -Parent) -ItemType Directory -Force -ErrorAction SilentlyContinue
                    ConvertFrom-MustacheTemplate -Template (Get-Content -Raw $item.FullName) -Values $Project | Out-File $destFile
                }
                if ([string]::IsNullOrEmpty($Template)) {
                    $found = Get-ChildItem $RedHatFolder -Recurse -Include "*.spec", "*.spec.mustache" | Select-Object -First 1
                    if ($found) { $Template = $found.FullName }
                }
            }
            # render the spec
            $null = $Project | Out-RPMSpecFile -Destination "$TopDir/SPECS" -Template $Template
            # tarball for Source0 : top-level entry is <name>-<version>/ so %setup -q finds it
            $TarPath = "$TopDir/SOURCES/$Name-$($SpecFields.Version).tar.gz"
            $null = Execute-Command -exe tar -args "-czf $TarPath -C $PayloadRoot $Name-$($SpecFields.Version)"
            # build
            $rc = Execute-Command -exe rpmbuild -args "--define '_topdir $TopDir' -bb $TopDir/SPECS/$Name.spec" -AsBool
            Write-Devel "rpmbuild rc = $rc"
            # locate the built rpm and copy it to the destination
            $built = Get-ChildItem $TopDir/RPMS -Recurse -Filter "$Name-$($SpecFields.Version)-*.rpm" -ErrorAction SilentlyContinue | Select-Object -First 1
            if ($built) {
                Copy-Item $built.FullName -Destination "$Destination/$Filename" -Force:$Force
                $value = (Resolve-Path "$Destination/$Filename").Path
            } else {
                $value = $false
            }
            # cleanup
            Remove-Item $TopDir -Recurse -Force -ErrorAction SilentlyContinue
        } else {
            $value = "$Destination/$Filename"
        }

        Write-Devel "value = $value"
        return $value
    }

    End {
        Write-LeaveFunction
    }
}