#!/bin/bash

# Stiftung Application - Backup Script for Synology NAS
# This script can be used for automated backups

set -e

# Configuration
BACKUP_DIR="./data/backups"
RETENTION_DAYS=30
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_NAME="stiftung_backup_${TIMESTAMP}.tar.gz"

echo "🔄 Starting backup process..."
echo "Timestamp: ${TIMESTAMP}"
echo "Backup name: ${BACKUP_NAME}"

# Create backup directory if it doesn't exist
mkdir -p "${BACKUP_DIR}"

# Check if containers are running
if ! docker-compose ps | grep -q "Up"; then
    echo "❌ Error: No containers are running. Please start the application first."
    exit 1
fi

# Create backup using the application's backup function
echo "📦 Creating backup using application backup function..."
if docker-compose exec -T web python manage.py backup --type=full --name="Automated backup ${TIMESTAMP}"; then
    echo "✅ Application backup completed successfully"
else
    echo "⚠️  Application backup failed, trying manual backup..."
    
    # Manual backup as fallback
    echo "📦 Creating manual backup..."
    
    # Create temporary backup directory
    TEMP_BACKUP_DIR="/tmp/stiftung_backup_${TIMESTAMP}"
    mkdir -p "${TEMP_BACKUP_DIR}"
    
    # Backup database
    echo "🗄️  Backing up database..."
    docker-compose exec -T db pg_dump -U stiftung_user stiftung > "${TEMP_BACKUP_DIR}/database.sql"
    
    # Backup uploads
    echo "📁 Backing up uploads..."
    if [ -d "./data/uploads" ]; then
        cp -r ./data/uploads "${TEMP_BACKUP_DIR}/"
    fi
    
    # Backup configuration
    echo "⚙️  Backing up configuration..."
    cp .env "${TEMP_BACKUP_DIR}/" 2>/dev/null || echo "No .env file to backup"
    cp docker-compose.yml "${TEMP_BACKUP_DIR}/"
    
    # Create tar.gz archive
    echo "📦 Creating archive..."
    tar -czf "${BACKUP_DIR}/${BACKUP_NAME}" -C "${TEMP_BACKUP_DIR}" .
    
    # Clean up temporary directory
    rm -rf "${TEMP_BACKUP_DIR}"
    
    echo "✅ Manual backup completed: ${BACKUP_NAME}"
fi

# Clean up old backups
echo "🧹 Cleaning up old backups (older than ${RETENTION_DAYS} days)..."
find "${BACKUP_DIR}" -name "stiftung_backup_*.tar.gz" -type f -mtime +${RETENTION_DAYS} -delete

# Show backup status
echo ""
echo "📊 Backup Summary:"
echo "=================="
echo "Latest backup: ${BACKUP_NAME}"
echo "Backup location: ${BACKUP_DIR}"
echo "Total backups: $(find "${BACKUP_DIR}" -name "stiftung_backup_*.tar.gz" | wc -l)"
echo "Available space: $(df -h "${BACKUP_DIR}" | tail -1 | awk '{print $4}')"

echo ""
echo "🎉 Backup process completed successfully!"
