#!/bin/bash
#
# wordpress-tools
# https://git.stack-source.com/msb/wordpress-tools
# MIT License Copyright (c) 2021 Matthew Saunders Brown

# must be root, will su to vhost users for wp cron runs
if [ "$USER" != "root" ]; then
  exec sudo $0
fi

declare -a virtualhostExclusionArray
# optionally add virtualhosts to virtualhostExclusionArray to have them skipped

# create virtualhostArray
cd /srv/www
virtualhostArray=(`ls -1|grep -v ^html$`)

for VHOST in "${virtualhostArray[@]}"
do
  # check if VHOST has been added to exclustion array
  if [[ ! " ${virtualhostExclusionArray[@]} " =~ " ${VHOST} " ]]; then
    # basic check for WP install
    if [ -f /srv/www/$VHOST/html/wp-config.php ]; then
      VHOST_USER=$(stat -c '%U' /srv/www/$VHOST)
      # confirm that WP really is installed
      if $(su -c "wp core is-installed --path=/srv/www/$VHOST/html/" $VHOST_USER); then
        # run cron for VHOST as VHOST_USER
        /usr/bin/logger --tag wp-cron "running wp-cli cron for $VHOST as $VHOST_USER"
        su -c "/usr/local/bin/wp cron event run --due-now --quiet --path=/srv/www/$VHOST/html/" $VHOST_USER
      fi
    fi
  fi
done