#!/bin/bash

# Backup Script
# Creates backups of data, configurations, and logs

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
BACKUP_DIR="${PROJECT_ROOT}/backups"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_NAME="gateway_backup_${TIMESTAMP}"

echo "💾 Creating backup: $BACKUP_NAME"
echo "Project root: $PROJECT_ROOT"
echo ""

cd "$PROJECT_ROOT"

# Create backup directory
mkdir -p "$BACKUP_DIR"

# Create backup archive
BACKUP_FILE="${BACKUP_DIR}/${BACKUP_NAME}.tar.gz"

echo "📦 Creating backup archive..."

# Files to backup
BACKUP_ITEMS=(
    "data/"
    "configs/"
    "logs/"
    "docker-compose.prod.yml"
    "go.mod"
    "go.sum"
)

# Check which items exist and add to backup
EXISTING_ITEMS=()
for item in "${BACKUP_ITEMS[@]}"; do
    if [ -e "$item" ]; then
        EXISTING_ITEMS+=("$item")
    else
        echo "⚠️  Skipping missing item: $item"
    fi
done

if [ ${#EXISTING_ITEMS[@]} -eq 0 ]; then
    echo "❌ No items found to backup"
    exit 1
fi

# Create the backup
tar -czf "$BACKUP_FILE" "${EXISTING_ITEMS[@]}" 2>/dev/null

if [ ! -f "$BACKUP_FILE" ]; then
    echo "❌ Backup creation failed"
    exit 1
fi

# Get backup size
BACKUP_SIZE=$(ls -lh "$BACKUP_FILE" | awk '{print $5}')
echo "✅ Backup created: $BACKUP_FILE ($BACKUP_SIZE)"

# Database-specific backup (if SQLite database exists)
if [ -f "data/metadata.db" ]; then
    echo "🗄️  Creating database backup..."
    DB_BACKUP="${BACKUP_DIR}/database_${TIMESTAMP}.sql"
    
    # Create SQL dump
    sqlite3 data/metadata.db .dump > "$DB_BACKUP"
    
    if [ -f "$DB_BACKUP" ]; then
        DB_SIZE=$(ls -lh "$DB_BACKUP" | awk '{print $5}')
        echo "✅ Database backup created: $DB_BACKUP ($DB_SIZE)"
    else
        echo "⚠️  Database backup failed"
    fi
fi

# Configuration backup
echo "⚙️  Backing up configuration..."
CONFIG_BACKUP="${BACKUP_DIR}/config_${TIMESTAMP}.tar.gz"
if [ -d "configs" ]; then
    tar -czf "$CONFIG_BACKUP" configs/
    CONFIG_SIZE=$(ls -lh "$CONFIG_BACKUP" | awk '{print $5}')
    echo "✅ Configuration backup: $CONFIG_BACKUP ($CONFIG_SIZE)"
fi

# Docker state backup
echo "🐳 Backing up Docker state..."
if command -v docker-compose >/dev/null 2>&1; then
    DOCKER_BACKUP="${BACKUP_DIR}/docker_state_${TIMESTAMP}.txt"
    {
        echo "=== Docker Compose Status ==="
        docker-compose -f docker-compose.prod.yml ps || true
        echo ""
        echo "=== Docker Images ==="
        docker images | grep torrent-gateway || true
        echo ""
        echo "=== Docker Volumes ==="
        docker volume ls | grep torrent || true
    } > "$DOCKER_BACKUP" 2>/dev/null
    echo "✅ Docker state backup: $DOCKER_BACKUP"
fi

# Cleanup old backups (keep last 10)
echo "🧹 Cleaning up old backups..."
BACKUP_COUNT=$(ls -1 "$BACKUP_DIR"/gateway_backup_*.tar.gz 2>/dev/null | wc -l)

if [ "$BACKUP_COUNT" -gt 10 ]; then
    OLD_BACKUPS=$(ls -1t "$BACKUP_DIR"/gateway_backup_*.tar.gz | tail -n +11)
    for backup in $OLD_BACKUPS; do
        echo "   Removing old backup: $(basename "$backup")"
        rm -f "$backup"
    done
fi

# Create backup manifest
MANIFEST_FILE="${BACKUP_DIR}/backup_manifest.txt"
{
    echo "Backup: $BACKUP_NAME"
    echo "Timestamp: $(date)"
    echo "Git commit: $(git rev-parse HEAD 2>/dev/null || echo 'unknown')"
    echo "Git branch: $(git branch --show-current 2>/dev/null || echo 'unknown')"
    echo "Files backed up:"
    for item in "${EXISTING_ITEMS[@]}"; do
        echo "  - $item"
    done
    echo ""
    echo "Backup files created:"
    ls -lh "$BACKUP_DIR"/*"$TIMESTAMP"* | awk '{print "  " $9 " (" $5 ")"}'
} > "$MANIFEST_FILE"

echo "✅ Backup manifest: $MANIFEST_FILE"

echo ""
echo "🎉 Backup completed successfully!"
echo "📁 Backup location: $BACKUP_DIR"
echo "📦 Main backup: $BACKUP_FILE ($BACKUP_SIZE)"
echo "🕐 Timestamp: $TIMESTAMP"
echo ""
echo "📝 To restore this backup:"
echo "   ./scripts/restore.sh $TIMESTAMP"