[CmdletBinding()] param( [Parameter(Mandatory)][string]$PackagePath, [string]$OutputDirectory, [string]$ExpectedSourceCommit, [Parameter(Mandatory)][string]$CertificateThumbprint ) $ErrorActionPreference='Stop' . (Join-Path $PSScriptRoot '..\DeveloperPackage.ps1') $package=Test-DeveloperPackage $PackagePath $release=Get-Content -Raw (Join-Path $PSScriptRoot 'Release.json') | ConvertFrom-Json $repo=(Resolve-Path (Join-Path $PSScriptRoot '..\..\..')).Path if(!$ExpectedSourceCommit){$ExpectedSourceCommit=(& git -C $repo rev-parse HEAD).Trim();if($LASTEXITCODE -ne 0){throw 'Cannot read the exact setup source revision.'}} if($ExpectedSourceCommit -notmatch '^[0-9a-f]{40}$' -or $package.version -ne $release.version -or $package.commit -ne $ExpectedSourceCommit){throw 'Release version or exact package source SHA does not match the requested version12 build.'} Invoke-Checked git @('-C',$repo,'merge-base','--is-ancestor',$release.atlasBaseline,$package.commit) if($release.productCode -eq $release.baselineProductCode -or $release.upgradeCode -ne '{641A087B-9779-458C-B290-BCBBAD49319A}'){throw 'Version12 requires a new major-upgrade ProductCode and the established UpgradeCode.'} foreach($relative in @('PlotDirector.WordAddIn.dll','Agent\PlotDirector.Companion.Agent.exe')){ if([Diagnostics.FileVersionInfo]::GetVersionInfo((Join-Path $PackagePath $relative)).FileVersion -ne $release.version){throw "Wrong application bytes/version: $relative"} } $mage='C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools\mage.exe' foreach($manifest in @('PlotDirector.WordAddIn.vsto','PlotDirector.WordAddIn.dll.manifest')){Invoke-Checked $mage @('-Verify',(Join-Path $PackagePath $manifest))} $cert=Get-Item "Cert:\CurrentUser\My\$CertificateThumbprint" if(!$cert.HasPrivateKey -or $cert.NotAfter -lt (Get-Date)){throw 'An existing valid signing certificate with private key is required.'} if(!$OutputDirectory){$OutputDirectory=Join-Path (Get-DownloadsFolder) "PlotDirectorCompanion-$($release.version)-$($package.commit.Substring(0,8))"} if((Test-Path $OutputDirectory) -and @(Get-ChildItem -LiteralPath $OutputDirectory -Force).Count -gt 0){throw 'Setup output must be a new empty directory. The version10 baseline is never overwritten.'} New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null $output=(Resolve-Path $OutputDirectory).Path $work=Join-Path $output 'build' New-Item -ItemType Directory -Path $work -Force | Out-Null # Reuse the tray's existing P branding for setup, shortcuts and Apps & Features. Add-Type -AssemblyName System.Drawing $bitmap=[Drawing.Bitmap]::new(64,64);$graphics=[Drawing.Graphics]::FromImage($bitmap) $graphics.Clear([Drawing.Color]::Transparent);$graphics.SmoothingMode='AntiAlias' $brush=[Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(116,67,46));$graphics.FillEllipse($brush,1,1,62,62) $font=[Drawing.Font]::new('Segoe UI',35,[Drawing.FontStyle]::Bold,[Drawing.GraphicsUnit]::Pixel) $format=[Drawing.StringFormat]::new();$format.Alignment='Center';$format.LineAlignment='Center' $graphics.DrawString('P',$font,[Drawing.Brushes]::White,[Drawing.RectangleF]::new(0,0,64,64),$format) $icon=[Drawing.Icon]::FromHandle($bitmap.GetHicon());$iconPath=Join-Path $work 'PlotDirector.ico';$stream=[IO.File]::Create($iconPath);$icon.Save($stream);$stream.Dispose();$graphics.Dispose();$font.Dispose();$brush.Dispose();$bitmap.Dispose() $installer=New-Object -ComObject WindowsInstaller.Installer function Invoke-Com($object,[string]$name,[object[]]$arguments){$values=@(foreach($value in $arguments){if($null -eq $value){$null}else{$value.PSObject.BaseObject}});$object.GetType().InvokeMember($name,[Reflection.BindingFlags]::InvokeMethod,$null,$object,$values)} function Set-Com($object,[string]$name,[object[]]$arguments){$values=@(foreach($value in $arguments){if($null -eq $value){$null}else{$value.PSObject.BaseObject}});$object.GetType().InvokeMember($name,[Reflection.BindingFlags]::SetProperty,$null,$object,$values)} $msi=Join-Path $output 'PlotDirectorCompanion.msi' if(Test-Path $msi){throw "Output already exists: $msi. Choose an empty output directory."} $database=Invoke-Com $installer 'OpenDatabase' @($msi,3) function Import-Table([string]$name,[string[]]$columns,[string[]]$types,[string[]]$keys,[object[]]$rows){ $lines=@(($columns -join "`t"),($types -join "`t"),((@($name)+$keys) -join "`t")) foreach($row in $rows){$lines+=(@($row) -join "`t")} [IO.File]::WriteAllLines((Join-Path $work "$name.idt"),$lines,[Text.Encoding]::ASCII) $null=Invoke-Com $database 'Import' @($work,"$name.idt") } $product=$release.productCode $upgrade=$release.upgradeCode Import-Table Property @('Property','Value') @('s72','l0') @('Property') @( ,@('ProductCode',$product); ,@('ProductVersion',$release.msiVersion); ,@('ProductLanguage','1033'); ,@('ProductName','PlotDirector Companion'); ,@('Manufacturer','Nick Beckley'); ,@('UpgradeCode',$upgrade); ,@('COMPANIONVERSION',$package.version); ,@('SOURCECOMMIT',$package.commit); ,@('ARPPRODUCTICON','PlotDirectorIcon'); ,@('ARPURLINFOABOUT','https://dev.plotdirector.com/'); ,@('ARPNOMODIFY','1'); ,@('ARPNOREPAIR','1'); ,@('MSIINSTALLPERUSER','1'); ,@('ADDLOCAL','Complete'); ,@('SecureCustomProperties','OLDPRODUCTS;NEWERPRODUCTS') ) Import-Table Directory @('Directory','Directory_Parent','DefaultDir') @('s72','S72','l255') @('Directory') @( ,@('TARGETDIR','','SourceDir'); ,@('LocalAppDataFolder','TARGETDIR','.'); ,@('ProgramsDir','LocalAppDataFolder','Programs'); ,@('INSTALLDIR','ProgramsDir','PDCOMP~1|PlotDirector Companion'); ,@('AGENTDIR','INSTALLDIR','Agent'); ,@('ProgramMenuFolder','TARGETDIR','.'); ,@('MENUFOLDER','ProgramMenuFolder','PDCOMP~1|PlotDirector Companion'); ,@('StartupFolder','TARGETDIR','.') ) $payload=@(Get-ChildItem $PackagePath -File | Where-Object {$_.Extension -ne '.pdb'} | Sort-Object Name)+@(Get-ChildItem (Join-Path $PackagePath 'Agent') -File | Where-Object {$_.Extension -ne '.pdb'} | Sort-Object Name) $componentRows=@();$fileRows=@();$featureRows=@();$ddf=@('.OPTION EXPLICIT','.Set CabinetNameTemplate=payload.cab',('.Set DiskDirectoryTemplate="'+$work+'"'),('.Set RptFileName="'+(Join-Path $work 'payload.rpt')+'"'),('.Set InfFileName="'+(Join-Path $work 'payload.inf')+'"'),'.Set CompressionType=MSZIP','.Set Cabinet=on','.Set Compress=on','.Set MaxDiskSize=0') $sequence=0;$agentFile=$null foreach($file in $payload){ $sequence++;$folder=if($file.Directory.Name -eq 'Agent'){'AGENTDIR'}else{'INSTALLDIR'} $identity=[Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes('PlotDirector.Companion/'+$folder+'/'+$file.Name)) $suffix=[Convert]::ToHexString($identity)[0..23] -join '';$id='F'+$suffix;$component='C'+$suffix $componentGuid=[guid]::new([byte[]]$identity[0..15]) $componentRows+=,@($component,('{'+$componentGuid.ToString().ToUpperInvariant()+'}'),$folder,'256','',$id) $fileVersion=[Diagnostics.FileVersionInfo]::GetVersionInfo($file.FullName).FileVersion if($fileVersion -notmatch '^\d+\.\d+\.\d+\.\d+$'){$fileVersion=''} $fileRows+=,@($id,$component,('PD'+$sequence.ToString('000')+'.DAT|'+$file.Name),[string]$file.Length,$fileVersion,'','16384',[string]$sequence) $featureRows+=,@('Complete',$component);$ddf+=('"'+$file.FullName+'" '+$id) if($file.Name -eq 'PlotDirector.Companion.Agent.exe'){$agentFile=$id} } # Registry is a separate component so Windows Installer owns removal and rollback. $componentRows+=,@('Registration','{73926FA6-015D-4B48-885D-C17EAA64AC15}','INSTALLDIR','260','','RegManifest') $featureRows+=,@('Complete','Registration') Import-Table Component @('Component','ComponentId','Directory_','Attributes','Condition','KeyPath') @('s72','S38','s72','i2','S255','S72') @('Component') $componentRows Import-Table File @('File','Component_','FileName','FileSize','Version','Language','Attributes','Sequence') @('s72','s72','l255','i4','S72','S20','I2','i4') @('File') $fileRows Import-Table Feature @('Feature','Feature_Parent','Title','Description','Display','Level','Directory_','Attributes') @('s38','S38','L64','L255','I2','i2','S72','i2') @('Feature') @(,@('Complete','','PlotDirector Companion','Word add-in and tray Companion','1','1','INSTALLDIR','24')) Import-Table FeatureComponents @('Feature_','Component_') @('s38','s72') @('Feature_','Component_') $featureRows Import-Table Media @('DiskId','LastSequence','DiskPrompt','Cabinet','VolumeLabel','Source') @('i2','i4','L64','S255','S32','S72') @('DiskId') @(,@('1',[string]$sequence,'','#payload.cab','','')) $key='Software\Microsoft\Office\Word\Addins\PlotDirector.WordAddIn' Import-Table Registry @('Registry','Root','Key','Name','Value','Component_') @('s72','i2','l255','L255','L0','s72') @('Registry') @( ,@('RegManifest','1',$key,'Manifest','file:///[INSTALLDIR]PlotDirector.WordAddIn.vsto|vstolocal','Registration'); ,@('RegLoad','1',$key,'LoadBehavior','#3','Registration'); ,@('RegName','1',$key,'FriendlyName','PlotDirector Word Companion','Registration'); ,@('RegDescription','1',$key,'Description','PlotDirector by Nick Beckley','Registration'); ,@('RegVersion','1','Software\PlotDirector\Companion','InstalledVersion',$package.version,'Registration') ) $shortcutColumns=@('Shortcut','Directory_','Name','Component_','Target','Arguments','Description','Hotkey','Icon_','IconIndex','ShowCmd','WkDir') $shortcutTypes=@('s72','s72','l128','s72','s255','S255','L255','I2','S72','I2','I2','S72') Import-Table Shortcut $shortcutColumns $shortcutTypes @('Shortcut') @( ,@('OpenCompanion','MENUFOLDER','PDCOMP~1|PlotDirector Companion','Registration',('[#'+$agentFile+']'),'--open','Open PlotDirector Companion','','PlotDirectorIcon','0','1','AGENTDIR'); ,@('StartCompanion','StartupFolder','PDCOMP~1|PlotDirector Companion','Registration',('[#'+$agentFile+']'),'','PlotDirector tray Companion','','PlotDirectorIcon','0','1','AGENTDIR') ) Import-Table RemoveFile @('FileKey','Component_','FileName','DirProperty','InstallMode') @('s72','s72','L255','s72','i2') @('FileKey') @(,@('RemoveMenu','Registration','','MENUFOLDER','2')) Import-Table Upgrade @('UpgradeCode','VersionMin','VersionMax','Language','Attributes','Remove','ActionProperty') @('s38','S20','S20','S255','i4','S255','s72') @('UpgradeCode','VersionMin','VersionMax','Language','Attributes') @( ,@($upgrade,'',$release.msiVersion,'','0','ALL','OLDPRODUCTS'); ,@($upgrade,$release.msiVersion,'','','2','','NEWERPRODUCTS') ) $actions=@( ,@('FindRelatedProducts','','25'); ,@('LaunchConditions','','100'); ,@('ValidateProductID','','700'); ,@('CostInitialize','','800'); ,@('FileCost','','900'); ,@('CostFinalize','','1000'); ,@('InstallValidate','','1400'); ,@('InstallInitialize','','1500'); ,@('RemoveExistingProducts','OLDPRODUCTS','1510'); ,@('ProcessComponents','','1600'); ,@('UnpublishFeatures','','1800'); ,@('RemoveShortcuts','','3200'); ,@('RemoveRegistryValues','','3300'); ,@('RemoveFiles','','3500'); ,@('RemoveFolders','','3600'); ,@('CreateFolders','','3700'); ,@('InstallFiles','','4000'); ,@('CreateShortcuts','','4500'); ,@('WriteRegistryValues','','5000'); ,@('RegisterUser','','6000'); ,@('RegisterProduct','','6100'); ,@('PublishFeatures','','6300'); ,@('PublishProduct','','6400'); ,@('InstallFinalize','','6600') ) Import-Table InstallExecuteSequence @('Action','Condition','Sequence') @('s72','S255','I2') @('Action') $actions Import-Table InstallUISequence @('Action','Condition','Sequence') @('s72','S255','I2') @('Action') @( ,@('FindRelatedProducts','','25'); ,@('CostInitialize','','800'); ,@('FileCost','','900'); ,@('CostFinalize','','1000'); ,@('ExecuteAction','','1300') ) Import-Table LaunchCondition @('Condition','Description') @('s255','l255') @('Condition') @( ,@('NOT ALLUSERS','PlotDirector Companion must be installed for the current Windows user only.'); ,@('Installed OR NOT NEWERPRODUCTS','A newer PlotDirector Companion is installed. Downgrade was refused.') ) [IO.File]::WriteAllLines((Join-Path $work 'payload.ddf'),$ddf,[Text.Encoding]::ASCII) Invoke-Checked makecab.exe @('/F',(Join-Path $work 'payload.ddf')) function Insert-Stream([string]$table,[string]$name,[string]$file){ $sql=if($table -eq '_Streams'){'INSERT INTO `_Streams` (`Name`, `Data`) VALUES (?, ?)'}else{'INSERT INTO `Icon` (`Name`, `Data`) VALUES (?, ?)'} $view=Invoke-Com $database 'OpenView' @($sql);$record=Invoke-Com $installer 'CreateRecord' @(2) $null=Set-Com $record 'StringData' @(1,$name);$null=Invoke-Com $record 'SetStream' @(2,$file);$null=Invoke-Com $view 'Execute' @($record);$null=Invoke-Com $view 'Close' @() } $view=Invoke-Com $database 'OpenView' @('CREATE TABLE `Icon` (`Name` CHAR(72) NOT NULL, `Data` OBJECT NOT NULL PRIMARY KEY `Name`)');$null=Invoke-Com $view 'Execute' @();$null=Invoke-Com $view 'Close' @() Insert-Stream '_Streams' 'payload.cab' (Join-Path $work 'payload.cab') Insert-Stream 'Icon' 'PlotDirectorIcon' $iconPath $summary=$database.GetType().InvokeMember('SummaryInformation',[Reflection.BindingFlags]::GetProperty,$null,$database,@(20)) # Word-count bit 8 declares a limited-privilege package; bit 2 means compressed. # Omitting bit 8 prompts for elevation even when ALLUSERS is empty. foreach($entry in @(@(1,1252),@(2,'Installation Database'),@(3,'PlotDirector Companion'),@(4,'Nick Beckley'),@(7,'x64;1033'),@(9,('{'+[guid]::NewGuid().ToString().ToUpperInvariant()+'}')),@(14,500),@(15,10),@(18,'PlotDirector Companion packaging'))){$null=Set-Com $summary 'Property' $entry} $null=Invoke-Com $summary 'Persist' @();$null=Invoke-Com $database 'Commit' @() [Runtime.InteropServices.Marshal]::FinalReleaseComObject($summary) | Out-Null [Runtime.InteropServices.Marshal]::FinalReleaseComObject($database) | Out-Null $view=$null;$record=$null;$summary=$null;$database=$null;$installer=$null [GC]::Collect();[GC]::WaitForPendingFinalizers();[GC]::Collect() $signature=Set-AuthenticodeSignature -FilePath $msi -Certificate $cert -HashAlgorithm SHA256 if(!$signature.SignerCertificate -or $signature.SignerCertificate.Thumbprint -ne $cert.Thumbprint -or $signature.Status -notin @('Valid','UnknownError','NotTrusted')){throw "MSI signing failed: $($signature.StatusMessage)"} $setup=Join-Path $output 'PlotDirectorCompanionSetup.exe' $generated=Join-Path $work 'SetupRelease.g.cs' @" using System.Reflection; [assembly: AssemblyVersion("$($release.version)")] [assembly: AssemblyFileVersion("$($release.version)")] internal static class SetupRelease { internal const string Version = "$($release.version)"; internal const string MsiVersion = "$($release.msiVersion)"; internal const string ProductCode = "$product"; internal const string UpgradeCode = "$upgrade"; } "@ | Set-Content $generated -Encoding UTF8 Invoke-Checked 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe' @('/nologo','/target:winexe','/platform:x64',('/win32icon:'+$iconPath),('/win32manifest:'+(Join-Path $PSScriptRoot 'Setup.manifest')),('/out:'+$setup),('/resource:'+$msi+',Companion.msi'),'/reference:System.Windows.Forms.dll','/reference:System.Management.dll',$generated,(Join-Path $PSScriptRoot 'InstallerInventory.cs'),(Join-Path $PSScriptRoot 'UpgradePolicy.cs'),(Join-Path $PSScriptRoot 'Setup.cs')) $signature=Set-AuthenticodeSignature -FilePath $setup -Certificate $cert -HashAlgorithm SHA256 if(!$signature.SignerCertificate -or $signature.SignerCertificate.Thumbprint -ne $cert.Thumbprint -or $signature.Status -notin @('Valid','UnknownError','NotTrusted')){throw "Setup signing failed: $($signature.StatusMessage)"} $installerCommit=(& git -C $repo rev-parse HEAD).Trim() @{version=$package.version;msiVersion=$release.msiVersion;applicationCommit=$package.commit;installerCommit=$installerCommit;atlasBaseline=$release.atlasBaseline;payloadPackage=(Resolve-Path $PackagePath).Path;setupSha256=(Get-FileHash $setup).Hash;msiSha256=(Get-FileHash $msi).Hash;productCode=$product;upgradeCode=$upgrade;builtUtc=[DateTime]::UtcNow.ToString('o')} | ConvertTo-Json | Set-Content (Join-Path $output 'setup-evidence.json') Write-Output "Complete installer: $setup"