Public/Sync-GhostTheme.ps1

function Sync-GhostTheme {
    <#
    .SYNOPSIS
        Uploads and activates a theme on the Ghost site, unless the site already has it.

    .DESCRIPTION
        Makes the theme of the site match a theme package, which is what a pipeline needs to put a theme live:
        it can run on every push, and only uploads when the theme really differs. The theme is a zip file, or the
        folder of a theme, which is packed as New-GhostTheme does it.

        Ghost does not let an integration ask which themes a site has. So the package gets a small file with a
        fingerprint of its own content, assets/ghost-theme-fingerprint.txt, and the site serves that file like
        any other file of its theme. Reading that address tells which package is live. When it has the
        fingerprint of this package, nothing is uploaded. When it has another one, or none, the package is
        uploaded and activated; -Force does that anyway.

        The fingerprint comes from the names and the content of the files, not from the version in
        package.json: a change without a new version is uploaded too. On a site that asks visitors for a
        password the file cannot be read, and the theme is uploaded every time.

        The theme replaces the one with the same name on the site, as with New-GhostTheme, and becomes the
        active theme. The routes of a site are not part of a theme: upload a changed routes.yaml in Ghost Admin.

    .EXAMPLE
        Sync-GhostTheme -Path ./dist/my-theme.zip

        Uploads and activates the theme when the site shows another one, and returns what was done.

    .EXAMPLE
        Sync-GhostTheme -Path ./my-theme -WhatIf

        Shows whether the theme in the folder would be uploaded.

    .EXAMPLE
        Sync-GhostTheme -Path ./dist/my-theme.zip; Sync-GhostPost -Path ./posts -Recurse

        Puts the theme live when it changed and then the posts, so that a post never needs a template that the
        site does not have yet.

    .LINK
        https://docs.ghost.org/admin-api/themes/overview

    .LINK
        https://docs.ghost.org/admin-api/themes/uploading-a-theme
    #>

    [CmdletBinding(SupportsShouldProcess)]
    [OutputType('Ghost.ThemeSync')]
    param(
        # The zip file of a theme, or the folder of a theme. The path is taken literally: wildcards are not
        # expanded.
        [Parameter(Mandatory, Position = 0)]
        [ValidateNotNullOrEmpty()]
        [string] $Path,

        # Name to store the theme under. Defaults to the name in its package.json or, without one there, to the
        # name of the zip file or the folder.
        [ValidateNotNullOrEmpty()]
        [string] $Name,

        # Upload and activate the theme even when the site already has it.
        [switch] $Force
    )

    begin {
        Test-GhostConnection
    }

    process {
        try {
            if (-not (Test-Path -LiteralPath $Path)) {
                throw "The theme '$Path' does not exist."
            }
            $source = (Resolve-Path -LiteralPath $Path).ProviderPath.TrimEnd('\', '/')

            if (Test-Path -LiteralPath $source -PathType Container) {
                $archive = ConvertTo-GhostThemeArchive -Path $source
                $themeName = [System.IO.Path]::GetFileName($source)
            }
            else {
                if ([System.IO.Path]::GetExtension($source) -ne '.zip') {
                    throw "'$Path' is neither a zip file nor the folder of a theme."
                }
                $archive = [System.IO.File]::ReadAllBytes($source)
                $themeName = [System.IO.Path]::GetFileNameWithoutExtension($source)
            }

            $package = Get-GhostThemeFingerprint -Archive $archive
            if ($package.Name) {
                $themeName = $package.Name
            }
            if ($PSBoundParameters.ContainsKey('Name')) {
                $themeName = $Name
            }

            # What the site serves now. The address differs per request, so that nothing in between answers
            # with an earlier copy of the file.
            $site = (New-URIString -Endpoint '/') -replace '/ghost/api/admin/.*$'
            $live = $null
            try {
                $check = @{
                    Uri             = '{0}/{1}?t={2}' -f $site, $package.MarkerPath, [datetime]::UtcNow.Ticks
                    UseBasicParsing = $true
                    TimeoutSec      = 30
                    ErrorAction     = 'Stop'
                }
                $ProgressPreference = 'SilentlyContinue'
                $response = Invoke-WebRequest @check
                $content = $response.Content
                if ($content -is [byte[]]) {
                    $content = [System.Text.Encoding]::UTF8.GetString($content)
                }
                if ([string] $content -match '^\s*(?<fingerprint>[0-9a-f]{64})\s*$') {
                    $live = $Matches['fingerprint']
                }
            }
            catch {
                # Not there: the site has a theme that was not put there by this command.
                Write-Verbose -Message "The site has no fingerprint of its theme: $($_.Exception.Message)"
            }

            $action = 'Unchanged'
            if ($Force -or $live -cne $package.Fingerprint) {
                $action = 'Updated'
                if (-not $PSCmdlet.ShouldProcess($site, "Upload and activate the theme '$themeName'")) {
                    return
                }

                # Ghost names a theme after the file it is uploaded with.
                $folder = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath ([guid]::NewGuid().ToString('N'))
                New-Item -Path $folder -ItemType Directory | Out-Null
                try {
                    $file = Join-Path -Path $folder -ChildPath "$themeName.zip"
                    [System.IO.File]::WriteAllBytes($file, $package.Archive)
                    $theme = New-GhostTheme -Path $file -Activate -Confirm:$false
                    $themeName = @($theme)[0].name
                }
                finally {
                    Remove-Item -LiteralPath $folder -Recurse -Force
                }
            }

            [pscustomobject]@{
                PSTypeName  = 'Ghost.ThemeSync'
                Action      = $action
                Name        = $themeName
                Version     = $package.Version
                Fingerprint = $package.Fingerprint
                Path        = $source
            }
        }
        catch {
            $PSCmdlet.ThrowTerminatingError($_)
        }
    }
}