#!/bin/bash
#
# WordPress Auto-Update Installation Script
# 
# This script sets up the WordPress auto-update functionality:
# - Creates log file with proper permissions
# - Installs cron job for automatic updates every 6 hours
# - Tests the auto-update script
#

set -e

SCRIPT_DIR="/root/whp/scripts"
LOG_FILE="/var/log/wordpress-auto-update.log"
CRON_LINE="0 2,8,14,20 * * * /usr/bin/php ${SCRIPT_DIR}/wordpress-auto-update.php >> ${LOG_FILE} 2>&1"

echo "Installing WordPress Auto-Update functionality..."

# Create log file with proper permissions
echo "Creating log file: ${LOG_FILE}"
touch "${LOG_FILE}"
chmod 644 "${LOG_FILE}"
chown root:root "${LOG_FILE}"

# Test the auto-update script (dry run)
echo "Testing auto-update script..."
if php "${SCRIPT_DIR}/wordpress-auto-update.php" --dry-run; then
    echo "✓ Auto-update script test successful"
else
    echo "✗ Auto-update script test failed"
    exit 1
fi

# Check if cron job already exists
if crontab -l 2>/dev/null | grep -q "wordpress-auto-update.php"; then
    echo "WordPress auto-update cron job already exists"
else
    echo "Installing cron job..."
    # Add the cron job
    (crontab -l 2>/dev/null; echo "${CRON_LINE}") | crontab -
    echo "✓ Cron job installed successfully"
fi

# Display current cron jobs
echo ""
echo "Current cron jobs:"
crontab -l | grep -E "(wordpress|#|^$)" || echo "No relevant cron jobs found"

echo ""
echo "WordPress Auto-Update installation completed!"
echo ""
echo "The auto-update script will run every 6 hours at: 2 AM, 8 AM, 2 PM, and 8 PM"
echo "Logs will be written to: ${LOG_FILE}"
echo ""
echo "Manual usage:"
echo "  Dry run:           php ${SCRIPT_DIR}/wordpress-auto-update.php --dry-run"
echo "  Update core only:  php ${SCRIPT_DIR}/wordpress-auto-update.php --type=core"
echo "  Update one site:   php ${SCRIPT_DIR}/wordpress-auto-update.php --site-id=123"
echo ""