#requires -Version 5.1
<#
.SYNOPSIS
  Full backup of SovereignRepository for shipment readiness Gate 9.
.EXAMPLE
  .\scripts\Backup-SovereignRepository.ps1 -SqlServer localhost -Database SovereignRepository
#>
[CmdletBinding()]
param(
  [string]$SqlServer = 'localhost',
  [string]$Database = 'SovereignRepository',
  [string]$BackupDir = ''
)

$ErrorActionPreference = 'Stop'
$repoRoot = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
if (-not $BackupDir) {
  $BackupDir = Join-Path $repoRoot '_backups'
}
New-Item -ItemType Directory -Path $BackupDir -Force | Out-Null

$ts = Get-Date -Format 'yyyyMMdd-HHmmss'
$fileName = "$Database-$ts.bak"
$backupPath = Join-Path $BackupDir $fileName

$sql = @"
BACKUP DATABASE [$Database]
TO DISK = N'$($backupPath.Replace("'", "''"))'
WITH INIT, COMPRESSION, CHECKSUM, STATS = 10;
"@

Write-Host "[backup] $Database -> $backupPath"
sqlcmd -S $SqlServer -E -Q $sql
if ($LASTEXITCODE -ne 0) { throw "BACKUP DATABASE failed (exit $LASTEXITCODE)" }
Write-Host "[backup] OK"
