# Gitea Database Backup Script
$timestamp = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
$backupDir = ".\backups"
$backupFile = "$backupDir\gitea-db-backup-$timestamp.sql"

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

# Create database dump
Write-Host "Creating database backup to $backupFile..."
docker exec gitea-db pg_dump -U gitea -d gitea > $backupFile

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

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