#!/bin/bash

# Setup Redis Monitoring Script
# This script sets up automated Redis monitoring and recovery

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MONITOR_SCRIPT="$SCRIPT_DIR/redis-monitor.sh"
CRON_JOB="*/5 * * * * $MONITOR_SCRIPT"

echo "🔧 Setting up Redis monitoring..."

# Make monitor script executable
chmod +x "$MONITOR_SCRIPT"

# Check if cron job already exists
if crontab -l 2>/dev/null | grep -q "$MONITOR_SCRIPT"; then
    echo "✅ Redis monitoring cron job already exists"
else
    # Add cron job
    (crontab -l 2>/dev/null; echo "$CRON_JOB") | crontab -
    echo "✅ Redis monitoring cron job added"
fi

# Create log file
LOG_FILE="/var/log/redis-monitor.log"
if [ ! -f "$LOG_FILE" ]; then
    sudo touch "$LOG_FILE"
    sudo chmod 644 "$LOG_FILE"
    echo "✅ Log file created at $LOG_FILE"
fi

# Test Redis connection
echo "🧪 Testing Redis connection..."
if docker exec cbt-redis redis-cli ping > /dev/null 2>&1; then
    echo "✅ Redis is responding"
else
    echo "⚠️  Warning: Redis is not responding"
fi

echo ""
echo "✨ Setup complete!"
echo ""
echo "📊 Monitoring details:"
echo "   - Check interval: Every 5 minutes"
echo "   - Log file: $LOG_FILE"
echo "   - Monitor script: $MONITOR_SCRIPT"
echo ""
echo "🔍 View logs: tail -f $LOG_FILE"
echo "📋 View cron: crontab -l"
echo "❌ Remove: crontab -e (then remove the redis-monitor line)"