#!/bin/bash
# Setup cron job for automated zone file synchronization
# Run this script on the server to install the daily sync job

set -e

echo "🔧 Setting up Pounce Zone Sync Cron Job"
echo "========================================"

# Create log directory
mkdir -p /home/user/logs
touch /home/user/logs/zone_sync.log

# Create the cron wrapper script
cat > /home/user/pounce/backend/scripts/run_zone_sync.sh << 'EOF'
#!/bin/bash
# Wrapper script for zone sync with proper environment

cd /home/user/pounce/backend
source venv/bin/activate

# Run sync with timeout (max 2 hours)
timeout 7200 python scripts/sync_all_zones.py >> /home/user/logs/zone_sync.log 2>&1

# Rotate log if too big (keep last 10MB)
if [ -f /home/user/logs/zone_sync.log ]; then
    size=$(stat -f%z /home/user/logs/zone_sync.log 2>/dev/null || stat -c%s /home/user/logs/zone_sync.log 2>/dev/null)
    if [ "$size" -gt 10485760 ]; then
        tail -c 5242880 /home/user/logs/zone_sync.log > /home/user/logs/zone_sync.log.tmp
        mv /home/user/logs/zone_sync.log.tmp /home/user/logs/zone_sync.log
    fi
fi
EOF

chmod +x /home/user/pounce/backend/scripts/run_zone_sync.sh

# Add cron job (runs daily at 06:00 UTC - after most registry updates)
# Remove existing pounce zone sync jobs first
crontab -l 2>/dev/null | grep -v "run_zone_sync.sh" > /tmp/crontab.tmp || true

# Add new job
echo "# Pounce Zone File Sync - Daily at 06:00 UTC" >> /tmp/crontab.tmp
echo "0 6 * * * /home/user/pounce/backend/scripts/run_zone_sync.sh" >> /tmp/crontab.tmp

# Install crontab
crontab /tmp/crontab.tmp
rm /tmp/crontab.tmp

echo ""
echo "✅ Cron job installed!"
echo ""
echo "Schedule: Daily at 06:00 UTC"
echo "Log file: /home/user/logs/zone_sync.log"
echo ""
echo "Current crontab:"
crontab -l
echo ""
echo "To run manually: /home/user/pounce/backend/scripts/run_zone_sync.sh"
echo "To view logs: tail -f /home/user/logs/zone_sync.log"
