#!/usr/bin/env bash
# wp-security-plugin-monitor.sh, run as root from cron. Alerts if a tracked
# WordPress security plugin has been disabled, renamed, deleted, or modified.
# Source: https://techearl.com/wordpress-security-plugin-silently-disabled
# Site:   https://techearl.com/

set -e
WP_ROOT="/var/www/wordpress"
WEB_USER="www-data"
ALERT_EMAIL="alerts@your-monitoring-account.com"
BASELINE_DIR="/var/lib/wp-security-monitor"
mkdir -p "$BASELINE_DIR"

# 1. Current state
sudo -u "$WEB_USER" wp plugin list --status=active --format=csv --fields=name \
  --path="$WP_ROOT" --allow-root > /tmp/active-now.txt

cd "$WP_ROOT/wp-content/plugins/wordfence" 2>/dev/null && \
  find . -type f -name '*.php' -exec sha256sum {} \; | sort > /tmp/hashes-now.txt

# 2. Compare to baseline (first run builds the baseline)
if [ ! -f "$BASELINE_DIR/active.txt" ]; then
  cp /tmp/active-now.txt "$BASELINE_DIR/active.txt"
  cp /tmp/hashes-now.txt "$BASELINE_DIR/hashes.txt"
  echo "Initial baseline created." | mail -s "WP security monitor: baseline" "$ALERT_EMAIL"
  exit 0
fi

ACTIVE_DIFF=$(diff "$BASELINE_DIR/active.txt" /tmp/active-now.txt || true)
HASH_DIFF=$(diff "$BASELINE_DIR/hashes.txt" /tmp/hashes-now.txt || true)

if [ -n "$ACTIVE_DIFF" ] || [ -n "$HASH_DIFF" ]; then
  {
    echo "WordPress security-plugin anomaly detected at $(date)."
    echo
    [ -n "$ACTIVE_DIFF" ] && { echo "--- active_plugins diff ---"; echo "$ACTIVE_DIFF"; }
    [ -n "$HASH_DIFF" ]   && { echo; echo "--- plugin file hash diff ---"; echo "$HASH_DIFF"; }
  } | mail -s "ALERT: WP security plugin changed on $(hostname)" "$ALERT_EMAIL"
fi
