# Gitea Database Restore Script
param (
    [Parameter(Mandatory=$true)]
    [string]$BackupFile
)

# Check if backup file exists
if (-not (Test-Path $BackupFile)) {
    Write-Host "Backup file not found: $BackupFile" -ForegroundColor Red
    exit 1
}

# Extract the backup if it's a zip file
$tempFile = $null
if ($BackupFile.EndsWith(".zip")) {
    $tempDir = [System.IO.Path]::GetTempPath()
    $tempFile = Join-Path $tempDir "gitea-db-restore-temp.sql"
    
    Write-Host "Extracting backup file..."
    Expand-Archive -Path $BackupFile -DestinationPath $tempDir -Force
    $extractedFile = Get-ChildItem -Path $tempDir -Filter "*.sql" | Select-Object -First 1
    
    if ($extractedFile) {
        Copy-Item $extractedFile.FullName -Destination $tempFile
        $BackupFile = $tempFile
    } else {
        Write-Host "Failed to extract SQL file from backup" -ForegroundColor Red
        exit 1
    }
}

# Confirm before proceeding
Write-Host "WARNING: This will overwrite the current database with the backup." -ForegroundColor Yellow
Write-Host "Make sure your Gitea service is stopped before proceeding." -ForegroundColor Yellow
$confirmation = Read-Host "Do you want to continue? (y/n)"

if ($confirmation -ne "y") {
    Write-Host "Restore cancelled."
    if ($tempFile -and (Test-Path $tempFile)) {
        Remove-Item $tempFile
    }
    exit 0
}

# Stop Gitea services
Write-Host "Stopping Gitea services..."
docker-compose stop

# Restore the database
Write-Host "Restoring database from backup..."
Get-Content $BackupFile | docker exec -i gitea-db psql -U gitea -d gitea

# Check restore status
if ($LASTEXITCODE -eq 0) {
    Write-Host "Database restore completed successfully!" -ForegroundColor Green
} else {
    Write-Host "Database restore failed!" -ForegroundColor Red
}

# Clean up temp file if created
if ($tempFile -and (Test-Path $tempFile)) {
    Remove-Item $tempFile
}

# Restart Gitea services
Write-Host "Starting Gitea services..."
docker-compose start 