#!/bin/bash 

export PATH="/usr/local/bin:/usr/bin:/bin"
export IFS=$'\n'
export LOGNAME=$(id -nu)
export HOST=$(hostname)

t=$'\t'

function usage(){
	echo "Usage: $0 event user-pattern" >&2
	echo >&2
	echo "Examples: $0 activate '[a-z0-9]{3}[0-9]{2}(-.+)?'" >&2
        echo "          HS_NEW_SERVER=\"$HOST\" $0 serverchange 'xyz00(-.+)?'" >&2
	echo >&2
	echo "This script can only be used by root." >&2
	echo "Enviroment variables that begin with \"HS_\" will be passed through to the commands." >&2
}

if [ "$*" == "-h" ]; then
	# display the help text
	usage
elif ( [ "$LOGNAME" == "root" ] && [ -n "$2" ] && [ -z "$3" ] ); then
	# loop through all accounts matching $2 and execute every $1 job
	event="$1"
	pattern="$2"
	
	# get all enviroment variables that have to be passed through to the jobs
	envs=$(declare | sed -n 's/^\(HS_[^=]*\)=\(.*\)$/export \1="\2"; /p' | tr -d $'\n')
	
	# - get the paths to the jobfiles of all matching accounts
	# - get all jobs that should be executed when the current event occurs
	# - change the formatting of the lines:
	#    homedirectory, whitespace, command
	jobs=($(egrep "^$pattern:" /etc/passwd | cut -d ":" -f 6 | sort -u |
		xargs -n 1 -i egrep -H "^[ $t]*@$event[ $t]+[^ $t]+" "{}/etc/event-handler" 2>/dev/null |
		sed -n "s/^\([^: $t]\+\)\/etc\/event-handler:[ $t]*@$event[ $t]\+\(.\+\)$/\1 \2/p" |
		sed -e 's/"/\\"/g'))

	# loop until the array of jobs is empty
	
	while [ ${#jobs[*]} != 0 ]; do
		# get a pseudo-random number
		random=$[ $RANDOM % ${#jobs[*]} ]
		
		# get the job to deal with
		job=${jobs[$random]}
		
		# delete the job out of the list
		unset jobs[$random]
		
		# remove the empty array element produced by unset
		jobs=(${jobs[*]})
		
		# extract the user as who the command should be executed out of /etc/passwd
		user=$(egrep "^([^:]+:){5}$(echo "$job" | cut -d " " -f 1):" /etc/passwd | cut -d ":" -f 1 | head -n 1)
		
		# get the command to execute
		command=$(echo "$job" | cut -d " " -f "2-")
		
		# $user may not be empty because otherwise the command might be executed as root which would be a security hole
		
		if [ -n "$user" ]; then
			# execute the command using su(1)
			
			# echo -n "$0: Executing \"$command\" as $user"
			logger -p daemon.info -t handle-event "Starting job for $user on event $event"
			
			su -s /bin/bash -c "(/bin/bash -c \"$envs$command\" 2>&1 | /usr/bin/mail -e -s 'Automated job <$user@$HOST> $command' $user) &" - $user >/dev/null 2>&1

			# load depending delay (1-180 secs)
			sleep `awk '{r=int(exp(1.4 * $1)); print (r<180)?r:180; exit }' /proc/loadavg`
			
			# echo "."
		else
			echo "$0: Could not find the user who owns the job \"$job\". Skipping." >&2
		fi
	done
else
	# invalid call
	usage
fi
