inogen/deployment/migrate-target.ps1

59 lines
2.5 KiB
PowerShell

[CmdletBinding()]
param(
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$SqlUser,
[switch]$TrustServerCertificate,
[switch]$ConfigureOnly
)
$ErrorActionPreference = 'Stop'
$settingsPath = Join-Path $PSScriptRoot 'backend\appsettings.Production.json'
$setupPath = Join-Path $PSScriptRoot 'tools\Inogen.Setup\Inogen.Setup.exe'
if (-not (Test-Path -LiteralPath $settingsPath -PathType Leaf) -or
-not (Test-Path -LiteralPath $setupPath -PathType Leaf)) {
throw 'Run this script from the extracted package that contains backend and tools/Inogen.Setup.'
}
$settings = Get-Content -LiteralPath $settingsPath -Raw | ConvertFrom-Json
$servers = @($settings.TargetDatabaseGuard.AllowedServers)
$databases = @($settings.TargetDatabaseGuard.AllowedDatabases)
if ($servers.Count -ne 1 -or $databases.Count -ne 1 -or
[string]::IsNullOrWhiteSpace($servers[0]) -or [string]::IsNullOrWhiteSpace($databases[0])) {
throw 'Set exactly one target server and database in backend/appsettings.Production.json.'
}
$secret = Read-Host 'SQL migration password' -AsSecureString
$pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secret)
try { $plainPassword = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($pointer) }
finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($pointer) }
try {
$builder = New-Object System.Data.SqlClient.SqlConnectionStringBuilder
$builder['Data Source'] = [string]$servers[0]
$builder['Initial Catalog'] = [string]$databases[0]
$builder['User ID'] = $SqlUser
$builder['Password'] = $plainPassword
$builder['Encrypt'] = $true
$builder['TrustServerCertificate'] = [bool]$TrustServerCertificate
$env:INOGEN_TARGET_CONNECTION = $builder.ConnectionString
$env:INOGEN_TARGET_ALLOWED_SERVER = [string]$servers[0]
$env:INOGEN_TARGET_ALLOWED_DATABASE = [string]$databases[0]
}
finally {
$plainPassword = $null
$secret = $null
$builder = $null
}
Write-Host "Target: $($servers[0])/$($databases[0])"
& $setupPath verify-target
if ($LASTEXITCODE -ne 0) { throw 'Target verification failed; migration was not started.' }
if ($ConfigureOnly) {
Write-Host 'Target connection is ready in this PowerShell session; migration was not run.'
return
}
& $setupPath list-migrations
if ($LASTEXITCODE -ne 0) { throw 'No database migrations were discovered; migration was not started.' }
& $setupPath migrate-target
if ($LASTEXITCODE -ne 0) { throw 'Target migration failed.' }
Write-Host 'Keep this PowerShell session open until the administrator account is created.'