55 lines
2.5 KiB
PowerShell
55 lines
2.5 KiB
PowerShell
[CmdletBinding()]
|
|
param(
|
|
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$SqlUser,
|
|
[ValidatePattern('^[A-Za-z0-9._-]{3,80}$')][string]$AppPoolName = 'Inogen-Api',
|
|
[switch]$TrustServerCertificate
|
|
)
|
|
|
|
$ErrorActionPreference = 'Stop'
|
|
Import-Module WebAdministration -ErrorAction Stop
|
|
if (-not (Test-Path "IIS:\AppPools\$AppPoolName")) { throw "IIS App Pool not found: $AppPoolName" }
|
|
$settingsPath = Join-Path $PSScriptRoot 'backend\appsettings.Production.json'
|
|
$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 runtime 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
|
|
$connection = $builder.ConnectionString
|
|
}
|
|
finally {
|
|
$plainPassword = $null
|
|
$secret = $null
|
|
$builder = $null
|
|
}
|
|
|
|
$baseFilter = "system.applicationHost/applicationPools/add[@name='$AppPoolName']/environmentVariables"
|
|
$itemFilter = "$baseFilter/add[@name='ConnectionStrings__TargetDatabase']"
|
|
$existing = Get-WebConfigurationProperty -PSPath 'MACHINE/WEBROOT/APPHOST' -Filter $itemFilter `
|
|
-Name 'value' -ErrorAction SilentlyContinue
|
|
if ($null -eq $existing) {
|
|
Add-WebConfigurationProperty -PSPath 'MACHINE/WEBROOT/APPHOST' -Filter $baseFilter `
|
|
-Name '.' -Value @{ name = 'ConnectionStrings__TargetDatabase'; value = $connection }
|
|
}
|
|
else {
|
|
Set-WebConfigurationProperty -PSPath 'MACHINE/WEBROOT/APPHOST' -Filter $itemFilter `
|
|
-Name 'value' -Value $connection
|
|
}
|
|
$connection = $null
|
|
Restart-WebAppPool -Name $AppPoolName
|
|
Write-Host "Runtime SQL connection was saved for IIS App Pool $AppPoolName."
|