#!/bin/bash
# backup-compose-files.sh
# Backs up all compose files from the cluster to local repo

set -e

BACKUP_DIR="/Users/timothy.bendt/developer/cloud-compose/infrastructure"
CONTROLLER="ubuntu@192.168.2.130"
DATE=$(date +%Y-%m-%d)

echo "📦 Backing up compose files from cluster..."
echo "Date: $DATE"
echo ""

# Backup Dokploy compose files
echo "📁 Backing up Dokploy compose files..."
ssh -o ConnectTimeout=10 -i ~/.ssh/id_ed25519 $CONTROLLER "find /etc/dokploy/compose -name 'docker-compose.yml' -type f" | while read file; do
    # Get the project name from the path
    project=$(echo $file | grep -oP 'compose/\K[^/]+' | head -1)
    if [ ! -z "$project" ]; then
        echo "  - $project"
        mkdir -p "$BACKUP_DIR/compose/$project"
        scp -o ConnectTimeout=10 -i ~/.ssh/id_ed25519 $CONTROLLER:"$file" "$BACKUP_DIR/compose/$project/"
    fi
done

# Backup Traefik configuration
echo "📁 Backing up Traefik configuration..."
mkdir -p "$BACKUP_DIR/traefik"
scp -r -o ConnectTimeout=10 -i ~/.ssh/id_ed25519 $CONTROLLER:/etc/dokploy/traefik/* "$BACKUP_DIR/traefik/" 2>/dev/null || echo "  (No Traefik config or permission denied)"

# Backup local compose files from home directory
echo "📁 Backing up local compose files..."
scp -o ConnectTimeout=10 -i ~/.ssh/id_ed25519 $CONTROLLER:~/minio-stack.yml "$BACKUP_DIR/stacks/" 2>/dev/null || true

# Create manifest
echo "📄 Creating backup manifest..."
cat > "$BACKUP_DIR/BACKUP_MANIFEST.md" << EOF
# Infrastructure Backup Manifest

**Backup Date:** $DATE
**Source:** $CONTROLLER

## Contents

### Compose Files
All Docker Compose files from Dokploy-managed projects:
\`\`\`
$(ls -1 $BACKUP_DIR/compose/)
\`\`\`

### Stack Files
Standalone stack definitions:
\`\`\`
$(ls -1 $BACKUP_DIR/stacks/ 2>/dev/null || echo "None")
\`\`\`

### Traefik Configuration
Reverse proxy configuration backed up to ./traefik/

## Restoration
To restore these configurations:
1. Copy compose files to /etc/dokploy/compose/<project>/code/
2. Copy stack files to ~/ on the controller
3. Copy Traefik config to /etc/dokploy/traefik/
4. Redeploy via Dokploy UI or docker stack deploy

## Services Backed Up
$(ssh -o ConnectTimeout=10 -i ~/.ssh/id_ed25519 $CONTROLLER "docker service ls --format '- {{.Name}}'" 2>/dev/null || echo "Unable to fetch service list")

---
Generated: $(date)
EOF

echo ""
echo "✅ Backup complete!"
echo "📁 Location: $BACKUP_DIR/"
echo "📄 Manifest: $BACKUP_DIR/BACKUP_MANIFEST.md"
