#!/bin/bash

# Nextcloud Cron Monitoring Script
# Monitors and shows the status of the Nextcloud cron job
# Created: $(date)

echo "=== Nextcloud Cron Job Monitor ==="
echo ""

# Check cron service status
echo "1. Cron Service Status:"
if ssh root@omv800 "systemctl is-active cron" | grep -q "active"; then
    echo "✅ Cron service is running"
else
    echo "❌ Cron service is not running"
fi

# Check if the cron script exists
echo ""
echo "2. Cron Script Status:"
if ssh root@omv800 "test -f /usr/local/bin/nextcloud-cron.sh"; then
    echo "✅ Cron script exists: /usr/local/bin/nextcloud-cron.sh"
    echo "   Permissions: $(ssh root@omv800 'ls -la /usr/local/bin/nextcloud-cron.sh')"
else
    echo "❌ Cron script not found"
fi

# Check www-data crontab
echo ""
echo "3. Cron Job Configuration:"
if ssh root@omv800 "crontab -u www-data -l 2>/dev/null"; then
    echo "✅ Cron job configured for www-data user"
else
    echo "❌ No cron job configured for www-data user"
fi

# Check recent log entries
echo ""
echo "4. Recent Cron Execution Logs:"
if ssh root@omv800 "test -f /var/log/nextcloud-cron.log"; then
    echo "✅ Log file exists: /var/log/nextcloud-cron.log"
    echo "   Recent entries:"
    ssh root@omv800 "tail -10 /var/log/nextcloud-cron.log" | while read line; do
        echo "     $line"
    done
else
    echo "❌ Log file not found"
fi

# Check Nextcloud container status
echo ""
echo "5. Nextcloud Container Status:"
CONTAINER_STATUS=$(ssh root@omv800 "docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}' | grep nextcloud" 2>/dev/null)
if [ -n "$CONTAINER_STATUS" ]; then
    echo "✅ Nextcloud container is running:"
    echo "$CONTAINER_STATUS" | while read line; do
        echo "     $line"
    done
else
    echo "❌ Nextcloud container not found or not running"
fi

# Test cron execution manually
echo ""
echo "6. Manual Cron Test:"
echo "Testing cron script execution..."
if ssh root@omv800 "/usr/local/bin/nextcloud-cron.sh"; then
    echo "✅ Manual cron test successful"
else
    echo "❌ Manual cron test failed"
fi

# Show next scheduled execution
echo ""
echo "7. Next Scheduled Execution:"
echo "The cron job runs every 5 minutes (*/5 * * * *)"
echo "Next execution will be at the next 5-minute interval"

# Show monitoring commands
echo ""
echo "=== Monitoring Commands ==="
echo "To monitor the cron job in real-time:"
echo "  ssh root@omv800 'tail -f /var/log/nextcloud-cron.log'"
echo ""
echo "To check cron job status:"
echo "  ssh root@omv800 'crontab -u www-data -l'"
echo ""
echo "To test manually:"
echo "  ssh root@omv800 '/usr/local/bin/nextcloud-cron.sh'"
echo ""
echo "To view system cron logs:"
echo "  ssh root@omv800 'journalctl -u cron -f'"
