#!/bin/bash

DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/opt/backups/rezepte-klaus"

# Create backup directory
mkdir -p $BACKUP_DIR

echo "🗄️  Starting backup process..."

# Load environment variables if available
if [ -f .env.production ]; then
    export $(cat .env.production | grep -v '^#' | xargs)
fi

# Database backup
echo "📊 Backing up database..."
if docker ps | grep -q rezepte-mysql-prod; then
    docker exec rezepte-mysql-prod mysqldump \
        -u rezepte_user \
        -p${MYSQL_PASSWORD:-change_this_password} \
        rezepte_klaus > $BACKUP_DIR/database_$DATE.sql
    
    if [ $? -eq 0 ]; then
        echo "✅ Database backup completed: database_$DATE.sql"
        # Compress the SQL file
        gzip $BACKUP_DIR/database_$DATE.sql
        echo "🗜️  Database backup compressed"
    else
        echo "❌ Database backup failed!"
    fi
else
    echo "⚠️  MySQL container not running, skipping database backup"
fi

# Uploads backup
echo "📁 Backing up uploads..."
if docker ps | grep -q rezepte-backend-prod; then
    docker cp rezepte-backend-prod:/app/uploads $BACKUP_DIR/uploads_$DATE
    
    if [ $? -eq 0 ]; then
        echo "✅ Uploads backup completed: uploads_$DATE"
        # Create tar archive
        tar -czf $BACKUP_DIR/uploads_$DATE.tar.gz -C $BACKUP_DIR uploads_$DATE
        rm -rf $BACKUP_DIR/uploads_$DATE
        echo "🗜️  Uploads backup compressed"
    else
        echo "❌ Uploads backup failed!"
    fi
else
    echo "⚠️  Backend container not running, skipping uploads backup"
fi

# Cleanup old backups (keep last 7 days)
echo "🧹 Cleaning up old backups..."
find $BACKUP_DIR -name "database_*.sql.gz" -mtime +7 -delete
find $BACKUP_DIR -name "uploads_*.tar.gz" -mtime +7 -delete

# Show backup summary
echo ""
echo "📊 Backup Summary:"
echo "Backup location: $BACKUP_DIR"
ls -lh $BACKUP_DIR/*$DATE* 2>/dev/null || echo "No new backups created"

echo ""
echo "📋 Recent backups:"
ls -lht $BACKUP_DIR/ | head -10

echo "✅ Backup process completed!"