# PostgreSQL backup for TheBet365 (dev/docker-compose defaults)
param(
  [string]$OutDir = ".\backups",
  [string]$DbName = "thebet365",
  [string]$DbUser = "thebet365",
  [string]$DbHost = "127.0.0.1",
  [int]$DbPort = 5432
)

$ErrorActionPreference = "Stop"
New-Item -ItemType Directory -Force -Path $OutDir | Out-Null

$stamp = Get-Date -Format "yyyyMMdd-HHmmss"
$tempFile = Join-Path $OutDir "thebet365-db-manual-$stamp.sql"
$outFile = "$tempFile.gz"

Write-Host "Backing up $DbName to $outFile ..."
$env:PGPASSWORD = $env:THEBET365_DB_PASSWORD
if (-not $env:PGPASSWORD) {
  Write-Warning "Set THEBET365_DB_PASSWORD if your Postgres requires a password."
}

pg_dump -h $DbHost -p $DbPort -U $DbUser -d $DbName -F p -f $tempFile

$inputStream = [System.IO.File]::OpenRead($tempFile)
$outputStream = [System.IO.File]::Create($outFile)
try {
  $gzipStream = [System.IO.Compression.GzipStream]::new($outputStream, [System.IO.Compression.CompressionMode]::Compress)
  try {
    $inputStream.CopyTo($gzipStream)
  } finally {
    $gzipStream.Dispose()
  }
} finally {
  $inputStream.Dispose()
  $outputStream.Dispose()
}
Remove-Item $tempFile -Force

$hash = (Get-FileHash -Algorithm SHA256 $outFile).Hash.ToLowerInvariant()
"$hash  $(Split-Path -Leaf $outFile)" | Set-Content -Encoding UTF8 "$outFile.sha256"
Write-Host "Done: $outFile"
Write-Host "Checksum: $outFile.sha256"
