# ==========================
# PostgresDump.ps1
# ==========================

# Get script folder and .env path
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$envFile = Join-Path $scriptDir "..\.env"

if (!(Test-Path $envFile)) {
    Write-Error "Missing .env file at $envFile"
    exit 1
}

# Parse .env into a hashtable
$envVars = @{}
Get-Content $envFile | ForEach-Object {
    # skip comments & empty lines
    if ($_ -match '^\s*#') { return }
    if ([string]::IsNullOrWhiteSpace($_)) { return }

    $parts = $_ -split '=', 2
    if ($parts.Count -eq 2) {
        $key = $parts[0].Trim()
        $val = $parts[1].Trim()
        $envVars[$key] = $val
    }
}

# Grab vars from hashtable
$PgHost = $envVars["DATABASE_HOST"]
$PgPort = $envVars["DATABASE_PORT"]
$PgUser = $envVars["DATABASE_USER"]
$PgPass = $envVars["DATABASE_PASSWORD"]
$PgDatabase = $envVars["DATABASE_DB"]

# Where to put dumps
$dumpFolder = Join-Path $scriptDir "..\db_backups"
if (!(Test-Path -Path $dumpFolder)) {
    Write-Host "Creating backup folder: $dumpFolder"
    New-Item -ItemType Directory -Path $dumpFolder -Force | Out-Null
}

# Timestamp filename
$timestamp = Get-Date -Format "yyyyMMdd_HHmm"
$dumpFile = Join-Path $dumpFolder "$($PgDatabase)_$timestamp.sql"

# Location of pg_dump.exe (adjust if different version/path)
$pgDumpExe = "D:\Program Files\PostgreSQL\17\bin\pg_dump.exe"

# Set env var password so pg_dump can pick it up
$env:PGPASSWORD = $PgPass

Write-Host "Starting dump of $PgDatabase@$PgHost..."

& $pgDumpExe `
    -h $PgHost `
    -p $PgPort `
    -U $PgUser `
    -d $PgDatabase `
    -F p `
    -f $dumpFile

if ($LASTEXITCODE -eq 0) {
    Write-Host "✅ Dump complete: $dumpFile"
}
else {
    Write-Error "❌ Dump failed (exit code $LASTEXITCODE)"
}

# clear password to be safe
Remove-Item Env:PGPASSWORD