Files
mtusi2026lab3/scripts/init-env.ps1
T

28 lines
1.1 KiB
PowerShell

$ErrorActionPreference = 'Stop'
$root = Split-Path -Parent $PSScriptRoot
$utf8 = [Text.UTF8Encoding]::new($false)
$secretDir = Join-Path $root 'secrets'
[void][IO.Directory]::CreateDirectory($secretDir)
$passwordFile = Join-Path $secretDir 'postgres_password'
if (-not (Test-Path -LiteralPath $passwordFile)) {
$bytes = New-Object byte[] 32
$rng = [Security.Cryptography.RandomNumberGenerator]::Create()
try { $rng.GetBytes($bytes) } finally { $rng.Dispose() }
$password = [BitConverter]::ToString($bytes).Replace('-', '').ToLowerInvariant()
[IO.File]::WriteAllText($passwordFile, $password, $utf8)
}
$password = [IO.File]::ReadAllText($passwordFile).Trim()
if ($password -cnotmatch '^[a-f0-9]{64}$') {
throw 'Expected the locally generated PostgreSQL password in secrets/postgres_password.'
}
[IO.File]::WriteAllText(
(Join-Path $secretDir 'database_url'),
"postgresql://messenger:${password}@postgres:5432/messenger",
$utf8
)
$envFile = Join-Path $root '.env'
if (-not (Test-Path -LiteralPath $envFile)) {
Copy-Item -LiteralPath (Join-Path $root '.env.example') -Destination $envFile
}
Write-Output 'Local configuration ready.'