#!/bin/bash

# Restore Script
# Restores the gateway from a backup

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
BACKUP_TIMESTAMP="$1"

if [ -z "$BACKUP_TIMESTAMP" ]; then
    echo "❌ Usage: $0 <backup_timestamp>"
    echo ""
    echo "Available backups:"
    ls -1 "$PROJECT_ROOT/backups"/gateway_backup_*.tar.gz 2>/dev/null | \
        sed 's/.*gateway_backup_\(.*\)\.tar\.gz/  \1/' || echo "  No backups found"
    exit 1
fi

BACKUP_DIR="${PROJECT_ROOT}/backups"
BACKUP_FILE="${BACKUP_DIR}/gateway_backup_${BACKUP_TIMESTAMP}.tar.gz"

echo "🔄 Restoring Torrent Gateway"
echo "Backup: $BACKUP_TIMESTAMP"
echo "File: $BACKUP_FILE"
echo ""

cd "$PROJECT_ROOT"

# Check if backup exists
if [ ! -f "$BACKUP_FILE" ]; then
    echo "❌ Backup file not found: $BACKUP_FILE"
    echo ""
    echo "Available backups:"
    ls -1 "$BACKUP_DIR"/gateway_backup_*.tar.gz 2>/dev/null | \
        sed 's/.*gateway_backup_\(.*\)\.tar\.gz/  \1/' || echo "  No backups found"
    exit 1
fi

# Stop running services
echo "🛑 Stopping services..."
if docker-compose -f docker-compose.prod.yml ps | grep -q "Up"; then
    docker-compose -f docker-compose.prod.yml down --timeout 30
    echo "✅ Services stopped"
else
    echo "ℹ️  No services running"
fi

# Create restore point
echo "💾 Creating restore point..."
if [ -d "data" ] || [ -d "configs" ] || [ -d "logs" ]; then
    RESTORE_POINT_TIMESTAMP=$(date +%Y%m%d_%H%M%S)
    RESTORE_POINT="${BACKUP_DIR}/pre_restore_${RESTORE_POINT_TIMESTAMP}.tar.gz"
    
    tar -czf "$RESTORE_POINT" data/ configs/ logs/ 2>/dev/null || true
    echo "✅ Restore point created: $RESTORE_POINT"
fi

# Remove existing data/configs/logs
echo "🧹 Removing existing data..."
for dir in data configs logs; do
    if [ -d "$dir" ]; then
        echo "   Removing $dir/"
        rm -rf "$dir"
    fi
done

# Extract backup
echo "📦 Extracting backup..."
tar -xzf "$BACKUP_FILE"

if [ ! -d "data" ]; then
    echo "❌ Backup extraction failed - data directory not found"
    exit 1
fi
echo "✅ Backup extracted successfully"

# Restore database from SQL backup if available
DB_BACKUP="${BACKUP_DIR}/database_${BACKUP_TIMESTAMP}.sql"
if [ -f "$DB_BACKUP" ]; then
    echo "🗄️  Restoring database from SQL backup..."
    
    # Remove any existing database
    rm -f data/metadata.db
    
    # Restore from SQL
    sqlite3 data/metadata.db < "$DB_BACKUP"
    echo "✅ Database restored from SQL backup"
fi

# Set proper permissions
echo "🔐 Setting permissions..."
chmod -R 755 data/ configs/ logs/ 2>/dev/null || true
echo "✅ Permissions set"

# Build and start services
echo "🔨 Building Docker images..."
docker build -f Dockerfile.prod -t torrent-gateway:$BACKUP_TIMESTAMP .
docker build -f Dockerfile.prod -t torrent-gateway:latest .

echo "🚀 Starting services..."
docker-compose -f docker-compose.prod.yml up -d

# Wait for services to be healthy
echo "⏳ Waiting for services to be healthy..."
TIMEOUT=60
COUNT=0

while [ $COUNT -lt $TIMEOUT ]; do
    if curl -sf http://localhost:9876/api/health > /dev/null; then
        echo "✅ Gateway is healthy"
        break
    fi
    
    COUNT=$((COUNT + 1))
    sleep 1
    echo "Waiting... ($COUNT/$TIMEOUT)"
done

if [ $COUNT -ge $TIMEOUT ]; then
    echo "❌ Gateway failed to become healthy within $TIMEOUT seconds"
    echo "Checking logs..."
    docker-compose -f docker-compose.prod.yml logs --tail=50 gateway
    exit 1
fi

# Run health checks
echo "🏥 Running health checks..."
./scripts/health_check.sh

if [ $? -ne 0 ]; then
    echo "❌ Health checks failed after restore"
    exit 1
fi

echo ""
echo "🎉 Restore completed successfully!"
echo "✅ Services restored from backup: $BACKUP_TIMESTAMP"
echo "✅ All health checks passed"
echo "✅ Gateway is running and healthy"
echo ""
echo "📊 Access points:"
echo "   Gateway API: http://localhost:9876"
echo "   Admin Panel: http://localhost:9876/admin"
echo "   Grafana:     http://localhost:3000"
echo ""
echo "📝 Monitor the restore:"
echo "   docker-compose -f docker-compose.prod.yml logs -f"