#!/bin/bash
#
# By Igor Gubenko (igubenko@Princeton.EDU) - Modified 06/29/2012
#
# Wrapper script to email with custom headers
#

declare -a headers_unparsed head
declare keyret valret

associate () {
	local ref key val index
	ref="$1"
	key="$2"
	val="$3"
	index="$(eval echo \${#$ref[@]})"
#echo "##$key##"
#echo "##$val##"
	eval ${ref}[$index]=\"$key\"; let "index += 1"
	eval ${ref}[$index]=\"$val\"

	return 0
}

valof () {
	local ref key numel i
	ref="$1"
	key="$2"
	let "numel = $(eval echo \${#$ref[@]}) - 1"

	for i in `seq 0 $numel`; do
		if [[ "$(eval echo \${${ref}[$i]})" == "$key" ]]; then
			let "i += 1"; valret="$(eval echo \${${ref}[$i]})"; return 0
		fi
	done
	return 1
}

nagios_path="/usr/local/monitoring/nagios"

# Get options - -h => help, and exit; -H => can be used 1+ times to provide additional headers for the email in form of header_name:value

ind=0
while getopts "hH:" option
do
	case $option in
		H)
			headers_unparsed[$ind]="$OPTARG###"
			let "ind += 1"
			;;
		h)
			echo "Usage: custommailsend [-h] [-H header1:headerdata [...]] email1 [...]"
			exit 1
			;;
        esac
done
shift $((OPTIND-1))

# Default headers - from and reply-to
associate head From "Groundwork Monitoring<groundwk@Princeton.EDU>"
associate head "Reply-to" "EPSM<epm-list@Princeton.EDU>"

#echo "#############${headers_unparsed[@]}#############"

# Record key => value (header_name => value) pairs in the "head" associative array
OLD_IFS="$IFS"
IFS="###"
for header in ${headers_unparsed[@]}
do
	if [[ -z "$header" ]]; then continue; fi
#echo "##$header##"
	key=${header%:*}
	value=${header#*:}
#echo "key: $key"
#echo "val: $value"
	associate head "$key" "$value"
done
IFS="$OLD_IFS"

# Record the destination email addresses. Quit if none were provided
emails="$*"
if [[ -z "$emails" ]]; then echo "Need at least one email to send to"; exit 1; fi
associate head To "$(echo $emails | sed 's/ /,/g')"

emllog="/tmp/eml.$$"
# Output all headers into the email file
ctr=0
while [ "$ctr" -ne "${#head[@]}" ];
do
	valof head ${head[ctr]}
	echo "${head[$ctr]}: $valret"
	let "ctr += 2"
done > $emllog

# Read actual email data from STDIN
while read ln; do
	echo "$ln" | sed 's/<[Bb][Rr]\/\?>/\n/g' >> $emllog
done

valof head Sub
if echo "$valret" | grep -q "is \(UP\|DOWN\)"; then
	hst=`echo $valret | sed -n 's/ is [A-Z]\+//p'`
	svc=""
else
	hst=`echo $valret | sed -n 's/\/.*//p'`
	svc=`echo $valret | sed -n 's/^[^\/]\+\///;s/ is [A-Z]\+//p'`
fi

excep_hosts="nebti amunra cctsf"

#if ! echo "$excep_hosts" | grep -q "\(^\|[[:space:]]\+\)${hst}\([[:space:]]\+\|$\)"; then
#	if grep -q "\(check orphaned, is the mod-gearman worker on queue\|Service Check Timed Out\|Nagios time-out\|Plugin timed out while executing system call\)" $emllog; then
#		if ! grep -q "^${hst}%%%%${svc}%%%%${emails}$" ${nagios_path}/var/timeout_block
#		then
#			echo "${hst}%%%%${svc}%%%%$emails" >> ${nagios_path}/var/timeout_block
#		fi
#		emails='igubenko@Princeton.EDU'
#		sed -i '1,/^[[:space:]]*To:/{ s/^[[:space:]]*To:.*/To: '"$emails"'/;}' $emllog
#
#		echo >> $emllog
#		echo "########## Modified by custommailsend to block ############" >> $emllog
#		echo >> $emllog
#
#		# Make a record in the log
#		{
#			echo "------------------------------"
#			cat $emllog
#			echo "------------------------------"
#		} >> /usr/local/monitoring/log/emnotify_blocked.log
#		echo >> /usr/local/monitoring/log/emnotify_blocked.log
#
#		#rm -f $emllog
#		#exit 0
#
#	elif grep -q "^${hst}%%%%${svc}%%%%${emails}$" ${nagios_path}/var/timeout_block
#	then
#		sed -i "/^${hst}%%%%${svc}%%%%${emails}$/d" ${nagios_path}/var/timeout_block
#
#		if grep -q "is \(OK\|UP\)" $emllog; then
#			emails='igubenko@Princeton.EDU'
#			sed -i '4 s/^To:.*/To: '"$emails"'/' $emllog
#
#			echo >> $emllog
#			echo "########## Modified by custommailsend to block ############" >> $emllog
#			echo >> $emllog
#
#			# Make a record in the log
#			{
#				echo "------------------------------"
#				cat $emllog
#				echo "------------------------------"
#			} >> /usr/local/monitoring/log/emnotify_blocked.log
#			echo >> /usr/local/monitoring/log/emnotify_blocked.log
#		fi
#
#		#rm -f $emllog
#		#exit 0
#	fi
#else
#	# Make a record in the log
#	{
#		echo "------------------------------"
#		cat $emllog
#		echo "------------------------------"
#	} >> /usr/local/monitoring/log/emnotify_nonblock.log
#fi

# And send it
/usr/sbin/sendmail -oem -oi -t $emails < $emllog >> /usr/local/monitoring/log/emnotify_err.log 2>&1

# Make a record in the log
{
	#valof head To
	echo "------------------------------"
	#echo -n "To:$valret; "
	#valof head Subject
	#echo -n "Sub=$valret;"
	cat $emllog
	echo "------------------------------"
} >> /usr/local/monitoring/log/emnotify.log
echo >> /usr/local/monitoring/log/emnotify.log

rm -f $emllog

exit 0
