99 lines
8.1 KiB
PowerShell

[CmdletBinding(SupportsShouldProcess=$true)]
param([string]$PackagePath,[switch]$Rollback,[switch]$StopAgent)
$ErrorActionPreference='Stop'
if($env:OS -ne 'Windows_NT'){throw 'This per-user developer registration command requires Windows.'}
. (Join-Path $PSScriptRoot 'DeveloperPackage.ps1')
if(Get-Process WINWORD -ErrorAction SilentlyContinue){throw 'Close Microsoft Word normally, including any save prompts, then rerun. Word was not terminated.'}
$root=Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'PlotDirector\WordCompanionDeveloper'
$registration=Get-WordCompanionRegistration
$keyName=if($registration){$registration.Name}else{'PlotDirector.WordAddIn'}
$registry=Join-Path 'HKCU:\Software\Microsoft\Office\Word\Addins' $keyName
$backup=Join-Path $root 'previous-registration.json'
$clickOnceBackup=Join-Path $root 'previous-clickonce.json'
function Save-InstallBackup([string]$path,$value) {
if(Test-Path -LiteralPath $path){
$history=Join-Path $root 'history'
New-Item -ItemType Directory -Path $history -Force|Out-Null
$name=(Get-Date -Format 'yyyyMMddHHmmss')+'-'+[guid]::NewGuid().ToString('N')+'-'+[IO.Path]::GetFileName($path)
Copy-Item -LiteralPath $path -Destination (Join-Path $history $name)
}
$value|ConvertTo-Json -Depth 4|Set-Content -LiteralPath $path -Encoding UTF8
}
function Get-CompanionClickOnce {
$found=@(Get-ChildItem 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall' -ErrorAction SilentlyContinue | ForEach-Object {
$entry=Get-ItemProperty $_.PSPath
if(($entry.PSObject.Properties.Name -contains 'DisplayName') -and $entry.DisplayName -eq 'PlotDirector.WordAddIn'){
if(!($entry.PSObject.Properties.Name -contains 'UrlUpdateInfo')){throw 'The installed Companion has no recoverable deployment location.'}
$uri=$null
if(![uri]::TryCreate([string]$entry.UrlUpdateInfo,[UriKind]::Absolute,[ref]$uri) -or !$uri.IsFile -or [IO.Path]::GetFileName($uri.LocalPath) -ne 'PlotDirector.WordAddIn.vsto' -or !(Test-Path -LiteralPath $uri.LocalPath)){throw 'The installed ClickOnce Companion manifest is unavailable. No installation was removed.'}
[pscustomobject]@{manifest=$uri.AbsoluteUri;version=$entry.DisplayVersion}
}
})
if($found.Count -gt 1){throw 'Multiple ClickOnce Companion installations exist; no installation was changed.'}
if($found.Count -eq 1){return $found[0]}
return $null
}
function Invoke-CompanionVsto([string]$operation,[string]$manifest) {
$installer=Join-Path $env:CommonProgramFiles 'Microsoft Shared\VSTO\10.0\VSTOInstaller.exe'
if(!(Test-Path -LiteralPath $installer)){throw 'Existing VSTO installer was not found. No runtime installation or repair was attempted.'}
$process=Start-Process -FilePath $installer -ArgumentList @($operation,('"'+$manifest+'"'),'/Silent') -Wait -PassThru -WindowStyle Hidden
if($process.ExitCode -ne 0){throw "VSTO $operation failed with exit code $($process.ExitCode). Previous deployment: $manifest. No system repair was attempted."}
}
function Stop-DeveloperAgent {
foreach($agent in @(Get-Process 'PlotDirector.Companion.Agent' -ErrorAction SilentlyContinue)){
if(!$StopAgent){throw 'The companion agent is running. Rerun with -StopAgent to explicitly stop this user-session agent. Word must already be closed.'}
if($agent.SessionId -ne (Get-Process -Id $PID).SessionId){throw 'Agent belongs to a different session; it was not stopped.'}
$processInfo=Get-CimInstance Win32_Process -Filter "ProcessId=$($agent.Id)"
$owner=Invoke-CimMethod -InputObject $processInfo -MethodName GetOwnerSid
if($owner.ReturnValue -ne 0 -or $owner.Sid -ne [Security.Principal.WindowsIdentity]::GetCurrent().User.Value){throw 'Agent is not owned by this user; it was not stopped.'}
if($PSCmdlet.ShouldProcess("Agent PID $($agent.Id)",'Stop for explicit developer installation')){Stop-Process -Id $agent.Id -ErrorAction Stop;$agent.WaitForExit(5000)|Out-Null}
}
}
if($Rollback){
if(!(Test-Path -LiteralPath $backup)){throw 'No previous per-user registration backup exists.'}
$saved=Get-Content -Raw $backup|ConvertFrom-Json
if($saved.PSObject.Properties.Name -contains 'registryKey'){if($saved.registryKey -notmatch '^[a-zA-Z0-9._ -]+$'){throw 'Invalid saved registration key.'};$registry=Join-Path 'HKCU:\Software\Microsoft\Office\Word\Addins' $saved.registryKey}
if($PSCmdlet.ShouldProcess($registry,'Restore previous per-user Word registration')){
Stop-DeveloperAgent
if(!$saved.existed -and (Test-Path -LiteralPath $clickOnceBackup)){
$previous=Get-Content -Raw -LiteralPath $clickOnceBackup|ConvertFrom-Json
$installed=Get-CompanionClickOnce
if($installed -and $installed.manifest -ne $previous.manifest){Invoke-CompanionVsto '/Uninstall' $installed.manifest}
if(!$installed -or $installed.manifest -ne $previous.manifest){Invoke-CompanionVsto '/Install' $previous.manifest}
}
if($saved.existed){New-Item -Path $registry -Force|Out-Null;foreach($name in @('Manifest','LoadBehavior','FriendlyName','Description')){Remove-ItemProperty -Path $registry -Name $name -ErrorAction SilentlyContinue};foreach($property in $saved.values.PSObject.Properties){$type=if($property.Name -eq "LoadBehavior"){"DWord"}else{"String"};New-ItemProperty -Path $registry -Name $property.Name -Value $property.Value -PropertyType $type -Force|Out-Null}}
elseif(Test-Path $registry){Remove-Item -LiteralPath $registry -Recurse}
Write-Output 'Previous registration restored. Signed packages were retained. Open Word to verify.'
}
return
}
if(!$PackagePath){throw 'Provide -PackagePath from Update-WordCompanion.ps1, or use -Rollback.'}
$package=Test-DeveloperPackage $PackagePath
$destination=Join-Path $root "versions\$($package.version)-$($package.commit.Substring(0,8))"
if($PSCmdlet.ShouldProcess($destination,'Stage signed package and register VSTO for this user only')){
Stop-DeveloperAgent
New-Item -ItemType Directory -Path $root -Force|Out-Null
if(!(Test-Path -LiteralPath $destination)){New-Item -ItemType Directory -Path $destination -Force|Out-Null;Copy-Item -Path (Join-Path $PackagePath '*') -Destination $destination -Recurse}
$null=Test-DeveloperPackage $destination
$manifest=([uri](Join-Path $destination 'PlotDirector.WordAddIn.vsto')).AbsoluteUri+'|vstolocal'
$installed=Get-CompanionClickOnce
if($installed -and ($installed.manifest+'|vstolocal') -ne $manifest){
# ClickOnce rejects the same product loaded from a different deployment location.
# Retain its exact URI and original signed files for supported VSTO rollback.
Save-InstallBackup $clickOnceBackup $installed
Invoke-CompanionVsto '/Uninstall' $installed.manifest
}
$current=Get-ItemProperty -Path $registry -ErrorAction SilentlyContinue
if($current -and $current.Manifest -eq $manifest){Write-Output "Version $($package.version) is already registered. No backup replaced.";return}
$values=@{};if($current){foreach($name in @('Manifest','LoadBehavior','FriendlyName','Description')){if($current.PSObject.Properties.Name -contains $name){$values[$name]=$current.$name}}}
Save-InstallBackup $backup @{registryKey=$keyName;existed=[bool]$current;values=$values}
try{
New-Item -Path $registry -Force|Out-Null
New-ItemProperty -Path $registry -Name Manifest -PropertyType String -Value $manifest -Force|Out-Null
New-ItemProperty -Path $registry -Name FriendlyName -PropertyType String -Value 'PlotDirector Word Companion' -Force|Out-Null
New-ItemProperty -Path $registry -Name Description -PropertyType String -Value 'PlotDirector by Nick Beckley' -Force|Out-Null
New-ItemProperty -Path $registry -Name LoadBehavior -PropertyType DWord -Value 3 -Force|Out-Null
}catch{throw "Registration failed; backup retained at $backup. Run this script with -Rollback. $($_.Exception.Message)"}
Write-Output "Registered version $($package.version), SHA $($package.commit), for this user. Previous installation files were preserved. Office still validates manifest signatures/trust; no trust store was changed. Open Word and qualify this build."
}