# 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"
$redundantBackupDir = "D:\Pr00jects\gitea-docker"

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

# Ensure redundant backup directory exists
if (-not (Test-Path $redundantBackupDir)) {
    try {
        New-Item -ItemType Directory -Path $redundantBackupDir -Force
    } catch {
        "[$timestamp] Warning: Could not create redundant backup directory at $redundantBackupDir. Error: $_" | Out-File -Append -FilePath $logFile
    }
}

# 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
    $zipFileName = "$backupFile.zip"
    Compress-Archive -Path $backupFile -DestinationPath $zipFileName -Force
    Remove-Item $backupFile
    "[$timestamp] Backup compressed to $zipFileName" | Out-File -Append -FilePath $logFile
    
    # Copy backup to redundant location
    if (Test-Path $redundantBackupDir) {
        try {
            $redundantBackupFile = Join-Path $redundantBackupDir (Split-Path -Leaf $zipFileName)
            Copy-Item -Path $zipFileName -Destination $redundantBackupFile -Force
            "[$timestamp] Backup copied to redundant location: $redundantBackupFile" | Out-File -Append -FilePath $logFile
        } catch {
            "[$timestamp] Error copying backup to redundant location: $_" | Out-File -Append -FilePath $logFile
        }
    } else {
        "[$timestamp] Warning: Redundant backup directory not found: $redundantBackupDir" | 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
} 