# Script to backup the entire Postgres Docker volume
$timestamp = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
$backupDir = ".\backups"
$volumeName = "gitea-docker_postgres-data"
$backupFile = "$backupDir\postgres-volume-backup-$timestamp.tar"

# Ensure backup directory exists
if (-not (Test-Path $backupDir)) {
    New-Item -ItemType Directory -Path $backupDir
}

# Check if volume exists
$volumeExists = docker volume ls --format "{{.Name}}" | Select-String -Pattern "^$volumeName$"
if (-not $volumeExists) {
    Write-Host "Volume $volumeName not found!" -ForegroundColor Red
    exit 1
}

# Create a temporary container to access the volume
Write-Host "Creating backup of Docker volume $volumeName..."
docker run --rm -v ${volumeName}:/volume -v ${PWD}/${backupDir}:/backup alpine tar -cf /backup/$(Split-Path $backupFile -Leaf) -C /volume ./

# Check if backup was successful
if ($LASTEXITCODE -eq 0 -and (Test-Path $backupFile) -and (Get-Item $backupFile).Length -gt 0) {
    Write-Host "Volume backup completed successfully to $backupFile!" -ForegroundColor Green
    
    # Optional: Compress the backup file
    Write-Host "Compressing backup file..."
    Compress-Archive -Path $backupFile -DestinationPath "$backupFile.zip" -Force
    Remove-Item $backupFile
    Write-Host "Backup compressed to $backupFile.zip" -ForegroundColor Green
} else {
    Write-Host "Volume backup failed!" -ForegroundColor Red
}

# Optional: Clean up old volume backups (keep last 5)
$oldBackups = Get-ChildItem -Path $backupDir -Filter "postgres-volume-backup-*.zip" | Sort-Object LastWriteTime -Descending | Select-Object -Skip 5
foreach ($backup in $oldBackups) {
    Remove-Item $backup.FullName
    Write-Host "Removed old volume backup: $($backup.Name)"
} 