# Gitea Database Backup Script
$timestamp = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$backupDir = Join-Path $scriptDir "backups"
$backupFile = Join-Path $backupDir "gitea-db-backup-$timestamp.sql"

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

# Log execution of the script
$logFile = Join-Path $backupDir "backup-log.txt"
"[$timestamp] Starting database backup..." | Out-File -Append -FilePath $logFile

# Check if Docker is running
$dockerRunning = $false
try {
    $dockerStatus = docker info 2>&1
    $dockerRunning = $LASTEXITCODE -eq 0
} catch {
    $dockerRunning = $false
}

if (-not $dockerRunning) {
    "[$timestamp] Error: Docker is not running. Backup failed." | Out-File -Append -FilePath $logFile
    exit 1
}

# Check if Gitea container is running
$containerRunning = docker ps --format "{{.Names}}" | Select-String -Pattern "gitea-db" -Quiet
if (-not $containerRunning) {
    "[$timestamp] Error: Gitea database container is not running. Backup failed." | Out-File -Append -FilePath $logFile
    exit 1
}

# Create database dump
"[$timestamp] Creating database backup to $backupFile..." | Out-File -Append -FilePath $logFile
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) {
    "[$timestamp] Backup completed successfully!" | Out-File -Append -FilePath $logFile
    
    # Optional: Compress the backup file
    Compress-Archive -Path $backupFile -DestinationPath "$backupFile.zip" -Force
    Remove-Item $backupFile
    "[$timestamp] Backup compressed to $backupFile.zip" | Out-File -Append -FilePath $logFile
} else {
    "[$timestamp] Backup failed!" | Out-File -Append -FilePath $logFile
}

# 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
    "[$timestamp] Removed old backup: $($backup.Name)" | Out-File -Append -FilePath $logFile
} 