# Script to restore the Postgres Docker volume from a backup
param (
    [Parameter(Mandatory=$true)]
    [string]$BackupFile
)

$volumeName = "gitea-docker_postgres-data"
$tempDir = Join-Path $env:TEMP "postgres-volume-restore"

# 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
$tarFile = $BackupFile
if ($BackupFile.EndsWith(".zip")) {
    # Create temp directory if it doesn't exist
    if (-not (Test-Path $tempDir)) {
        New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
    } else {
        # Clean temp directory
        Remove-Item -Path "$tempDir\*" -Force -Recurse -ErrorAction SilentlyContinue
    }
    
    Write-Host "Extracting backup file..."
    Expand-Archive -Path $BackupFile -DestinationPath $tempDir -Force
    $extractedFile = Get-ChildItem -Path $tempDir -Filter "*.tar" | Select-Object -First 1
    
    if ($extractedFile) {
        $tarFile = $extractedFile.FullName
    } else {
        Write-Host "Failed to extract TAR file from backup" -ForegroundColor Red
        exit 1
    }
}

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

if ($confirmation -ne "y") {
    Write-Host "Restore cancelled."
    exit 0
}

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

# Check if volume exists and remove it
$volumeExists = docker volume ls --format "{{.Name}}" | Select-String -Pattern "^$volumeName$"
if ($volumeExists) {
    Write-Host "Removing existing volume $volumeName..."
    docker volume rm $volumeName
    if ($LASTEXITCODE -ne 0) {
        Write-Host "Failed to remove existing volume. It might be in use by another container." -ForegroundColor Red
        exit 1
    }
}

# Create a new volume
Write-Host "Creating new volume $volumeName..."
docker volume create $volumeName

# Restore from backup
Write-Host "Restoring volume from backup..."
docker run --rm -v ${volumeName}:/volume -v ${tarFile}:/backup.tar alpine sh -c "cd /volume && tar -xf /backup.tar"

if ($LASTEXITCODE -eq 0) {
    Write-Host "Volume restore completed successfully!" -ForegroundColor Green
} else {
    Write-Host "Volume restore failed!" -ForegroundColor Red
    exit 1
}

# Clean up temp directory if created
if ($BackupFile.EndsWith(".zip") -and (Test-Path $tempDir)) {
    Remove-Item -Path $tempDir -Force -Recurse -ErrorAction SilentlyContinue
}

# Start Gitea services
Write-Host "Starting Gitea services..."
docker-compose up -d

Write-Host "Restore process completed. Check if your Gitea instance is working properly." -ForegroundColor Green 