#!/bin/bash
# ============================================
# Document Translation API - Backup Script
# ============================================
# Usage: ./scripts/backup.sh [backup_dir]

set -e

# Configuration
BACKUP_DIR="${1:-./backups}"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_NAME="translate_backup_$TIMESTAMP"

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo -e "${YELLOW}Starting backup: $BACKUP_NAME${NC}"

# Create backup directory
mkdir -p "$BACKUP_DIR/$BACKUP_NAME"

# Backup uploaded files
if [ -d "./uploads" ]; then
    echo "Backing up uploads..."
    cp -r ./uploads "$BACKUP_DIR/$BACKUP_NAME/"
fi

# Backup output files
if [ -d "./outputs" ]; then
    echo "Backing up outputs..."
    cp -r ./outputs "$BACKUP_DIR/$BACKUP_NAME/"
fi

# Backup configuration
echo "Backing up configuration..."
cp .env* "$BACKUP_DIR/$BACKUP_NAME/" 2>/dev/null || true
cp docker-compose*.yml "$BACKUP_DIR/$BACKUP_NAME/" 2>/dev/null || true

# Backup Docker volumes (if using Docker)
if command -v docker &> /dev/null; then
    echo "Backing up Docker volumes..."
    
    # Get volume names
    VOLUMES=$(docker volume ls --format "{{.Name}}" | grep translate || true)
    
    for vol in $VOLUMES; do
        echo "  Backing up volume: $vol"
        docker run --rm \
            -v "$vol:/data:ro" \
            -v "$(pwd)/$BACKUP_DIR/$BACKUP_NAME:/backup" \
            alpine tar czf "/backup/${vol}.tar.gz" -C /data . 2>/dev/null || true
    done
fi

# Compress backup
echo "Compressing backup..."
cd "$BACKUP_DIR"
tar czf "${BACKUP_NAME}.tar.gz" "$BACKUP_NAME"
rm -rf "$BACKUP_NAME"

# Cleanup old backups (keep last 7)
echo "Cleaning old backups..."
ls -t translate_backup_*.tar.gz 2>/dev/null | tail -n +8 | xargs rm -f 2>/dev/null || true

echo -e "${GREEN}Backup complete: $BACKUP_DIR/${BACKUP_NAME}.tar.gz${NC}"
