#!/bin/bash

# Automated Backup Cron Setup Script
# This script sets up automated backups for production

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BACKUP_SCRIPT="$SCRIPT_DIR/run_backup.sh"

echo "🛡️  Database Backup Cron Setup"
echo "================================"
echo ""

# Make backup script executable
chmod +x "$BACKUP_SCRIPT"
echo "✅ Made run_backup.sh executable"

# Get current crontab
crontab -l > /tmp/current_cron 2>/dev/null || touch /tmp/current_cron

# Check if backup job already exists
if grep -q "run_backup.sh" /tmp/current_cron; then
    echo "⚠️  Backup cron job already exists!"
    echo ""
    echo "Current backup schedule:"
    grep "run_backup.sh" /tmp/current_cron
    echo ""
    read -p "Do you want to replace it? (y/n): " replace
    if [ "$replace" != "y" ]; then
        echo "Cancelled."
        exit 0
    fi
    # Remove existing backup job
    grep -v "run_backup.sh" /tmp/current_cron > /tmp/new_cron
else
    cp /tmp/current_cron /tmp/new_cron
fi

echo ""
echo "Select backup schedule:"
echo "1) Every 1 minute (for testing)"
echo "2) Weekly (Sunday at 2:00 AM)"
echo "3) Daily (at 2:00 AM)"
read -p "Enter choice (1-3): " choice

case $choice in
    1)
        # Every 1 minute for testing
        echo "* * * * * cd $SCRIPT_DIR && ./run_backup.sh" >> /tmp/new_cron
        echo "✅ Set to run EVERY 1 MINUTE (testing only!)"
        echo "⚠️  WARNING: This will create many backups. Change to weekly after testing!"
        ;;
    2)
        # Weekly - Sunday at 2 AM
        echo "0 2 * * 0 cd $SCRIPT_DIR && ./run_backup.sh" >> /tmp/new_cron
        echo "✅ Set to run WEEKLY on Sundays at 2:00 AM"
        ;;
    3)
        # Daily at 2 AM
        echo "0 2 * * * cd $SCRIPT_DIR && ./run_backup.sh" >> /tmp/new_cron
        echo "✅ Set to run DAILY at 2:00 AM"
        ;;
    *)
        echo "❌ Invalid choice"
        exit 1
        ;;
esac

# Install new crontab
crontab /tmp/new_cron
rm /tmp/current_cron /tmp/new_cron

echo ""
echo "✅ Cron job installed successfully!"
echo ""
echo "Current crontab:"
crontab -l | grep "run_backup.sh"
echo ""
echo "📝 Logs will be written to: $SCRIPT_DIR/backup.log"
echo ""
echo "To view logs:"
echo "  tail -f $SCRIPT_DIR/backup.log"
echo ""
echo "To remove cron job:"
echo "  crontab -e"
echo "  (then delete the line with run_backup.sh)"
echo ""

if [ "$choice" = "1" ]; then
    echo "⚠️  TESTING MODE: Backup runs every minute"
    echo "Wait 2-3 minutes and check:"
    echo "  1. tail -f $SCRIPT_DIR/backup.log"
    echo "  2. Check R2 bucket for new files"
    echo ""
    echo "To change to weekly schedule after testing:"
    echo "  ./setup_cron.sh"
    echo "  (select option 2)"
fi
