#!/bin/bash

# Nextcloud Cron Setup Script
# Sets up system cron to call Nextcloud cron.php every 5 minutes
# Created: $(date)

set -e

echo "=== Setting up Nextcloud Cron Job ==="
echo ""

# Create the cron script
echo "Creating cron script..."
CRON_SCRIPT="/usr/local/bin/nextcloud-cron.sh"

cat > /tmp/nextcloud-cron.sh << 'EOF'
#!/bin/bash

# Nextcloud Cron Script
# Executes cron.php inside the Nextcloud container
# Created: $(date)

# Get the Nextcloud container ID
CONTAINER_ID=$(docker ps -q -f name=nextcloud | head -1)

if [ -z "$CONTAINER_ID" ]; then
    echo "$(date): Nextcloud container not found" >> /var/log/nextcloud-cron.log
    exit 1
fi

# Execute cron.php inside the container as www-data user
if docker exec -u 33 "$CONTAINER_ID" php /var/www/html/cron.php; then
    echo "$(date): Nextcloud cron executed successfully" >> /var/log/nextcloud-cron.log
else
    echo "$(date): Nextcloud cron failed" >> /var/log/nextcloud-cron.log
    exit 1
fi
EOF

# Copy the script to the target system
echo "Copying cron script to OMV800..."
scp /tmp/nextcloud-cron.sh root@omv800:/tmp/nextcloud-cron.sh

# Set up the cron job on OMV800
echo "Setting up cron job on OMV800..."
ssh root@omv800 << 'ENDSSH'
# Move the script to the proper location
mv /tmp/nextcloud-cron.sh /usr/local/bin/nextcloud-cron.sh
chmod +x /usr/local/bin/nextcloud-cron.sh

# Create log file
touch /var/log/nextcloud-cron.log
chmod 644 /var/log/nextcloud-cron.log

# Add cron job for www-data user
echo "Setting up cron job for www-data user..."
if ! crontab -u www-data -l 2>/dev/null | grep -q "nextcloud-cron"; then
    # Create or append to www-data crontab
    (crontab -u www-data -l 2>/dev/null; echo "*/5 * * * * /usr/local/bin/nextcloud-cron.sh") | crontab -u www-data
    echo "✅ Cron job added for www-data user"
else
    echo "ℹ️  Cron job already exists for www-data user"
fi

# Verify the cron job was added
echo "Verifying cron job..."
crontab -u www-data -l

# Test the script manually
echo "Testing cron script..."
if /usr/local/bin/nextcloud-cron.sh; then
    echo "✅ Cron script test successful"
else
    echo "❌ Cron script test failed"
fi

# Show recent log entries
echo "Recent cron log entries:"
tail -5 /var/log/nextcloud-cron.log 2>/dev/null || echo "No log entries yet"
ENDSSH

# Clean up local temp file
rm -f /tmp/nextcloud-cron.sh

echo ""
echo "=== Nextcloud Cron Setup Complete ==="
echo "✅ Cron script created: /usr/local/bin/nextcloud-cron.sh"
echo "✅ Cron job added: Every 5 minutes for www-data user"
echo "✅ Log file: /var/log/nextcloud-cron.log"
echo ""
echo "The cron job will run every 5 minutes and execute Nextcloud's cron.php"
echo "inside the Docker container using the www-data user (UID 33)."
echo ""
echo "To monitor the cron job:"
echo "  - View logs: tail -f /var/log/nextcloud-cron.log"
echo "  - Check cron jobs: crontab -u www-data -l"
echo "  - Test manually: /usr/local/bin/nextcloud-cron.sh"
