#!/bin/sh
# This script tries to be smart and call the cron PHP script for
# all drupal sites on this host. As with any program that tries
# to be smart, it may very well screw up...

# Do you want to log the URLs accessed? Define a reasonable
# value to this variable
#LOGFILE=/var/log/drupal-cron.log
LOGFILE=""

function log () {
	if [ X$LOGFILE != X ]; then
		echo "`date` drupal_cron: $*" >> $LOGFILE
	fi
}

function try_config_file () {
	# Maybe the URL for each drupal site is defined in the configuration files...

	local BASE_URL="" FOUND=1

	for file in $1/baseurl.php $site/settings.php; do
		[ -f "$file" ] && BASE_URL=`grep '^$base_url' $file | cut -d"'" -f2`
		if [ X$BASE_URL != X ]; then
			FOUND=0
			break
		fi
	done

	echo "$BASE_URL"
	return $FOUND
}

function try_word_split () {
	# According to the docs, when a request is received, drupal concatenates
	# the server and directory names from the request to find the configuration
	# directory. We cannot do that, but we can try to do something similar:
	# just try to split the directory components in search of a valid hostname
	# THIS IS A HACK

	local BASE_URL="" prefix=`basename $1` suffix="" FOUND=1

	while echo $prefix | grep -q '\.'; do
		if ping -c 1 $prefix > /dev/null 2>&1; then
			FOUND=0
			break
		fi
		suffix=`echo $prefix | sed 's/^.*\.\([^. ]\+\)$/\1/'`.$suffix
		prefix=`echo $prefix | sed 's/\.[^. ]\+$//'`
	done

	if [ $FOUND = 0 ]; then
		# Sanitize...
		suffix=`echo $suffix | sed 's/\.$//'`
		BASE_URL=http://$prefix/$suffix
		BASE_URL=`echo $BASE_URL | sed 's;/$;;'`
	fi

	echo $BASE_URL
	return $FOUND
}

function do_all_sites () {

	local BASE_URL="" FOUND=1
	for site in /etc/drupal/5/sites/* ; do

		BASE_URL=`try_config_file $site` || BASE_URL=`try_word_split $site`

		if [ X$BASE_URL != X ] ; then
			curl --silent --compressed --location $BASE_URL/cron.php
			FOUND=0
			log fetched $BASE_URL/cron.php
		fi
	done

	return $FOUND
}

### THIS IS WHERE EVERYTHING BEGINS

if ! do_all_sites; then
	# no site found - fall back to localhost (only once)
	curl --silent --compressed --location http://localhost/drupal5/cron.php
	log falling back to fetch http://localhost/drupal5/cron.php
fi
