#!/bin/sh
#
# Script to check OWA 2010 login
#
# By Igor Gubenko (igubenko@princeton.edu)
#

OK=0
WARNING=1
CRITICAL=2
UNKNOWN=3

name=`basename $0`
url="$1"
username="$2"
password="$3"

if [ "$#" != "3" ]; then
	echo "Usage: $name <Exchange_OWA_URL> <username> <password>"
	exit $UNKNOWN
fi

SED=`which sed 2>/dev/null`
#PERL=`which perl 2>/dev/null`
PERL='/usr/local/bin/perl'
CURL=`which curl 2>/dev/null`

if [ "$SED" == "" -o "$PERL" == "" -o "$CURL" == "" ]; then
	echo "$name: One or more of the required components, sed, perl, and/or curl, could not be located on \$PATH"
	exit $UNKNOWN
fi

post_field1="destination=$1/owa"
post_field2="flags=4"
post_field3="forcedownlevel=0"
post_field4="trusted=4"
post_field5="username="`echo -n $username | $PERL -MURI::Escape -e 'print uri_escape(<STDIN>,"\x20-\x7E");'`
post_field6="password="`echo -n $password | $PERL -MURI::Escape -e 'print uri_escape(<STDIN>,"\x20-\x7E");'`
post_field7="isUtf8=1"
post_suffix="owa/auth/owaauth.dll"

if [ "$post_field5" == "username=" -o "$post_field6" == "password=" ]; then
	echo "$name: Error encoding the username, and/or the password. Please check.\n"
	exit $UNKNOWN
fi

echo $CURL -k -A 'Mozilla/5.0' -c /tmp/$$_cookies.txt --location-trusted -d $post_field1\
								-d $post_field2\
								-d $post_field3\
								-d $post_field4\
								-d $post_field5\
								-d $post_field6\
								-d $post_field7\
	${url}/$post_suffix >/tmp/$$_debug 2>&1
echo "PERL = '$PERL'; SED = '$SED'; CURL = '$CURL'" >> /tmp/$$_debug

$CURL -k -A 'Mozilla/5.0' -c /tmp/$$_cookies.txt --location-trusted -d $post_field1\
								-d $post_field2\
								-d $post_field3\
								-d $post_field4\
								-d $post_field5\
								-d $post_field6\
								-d $post_field7\
	${url}/$post_suffix >/tmp/$$_results 2>&1

ext_code="$?"

if [ "$ext_code" -ne "0" ]; then
	echo "$name: cURL returned a non-zero exit code $ext_code. Possibly could not connect?"
	rm -f /tmp/$$*
	exit $UNKNOWN
fi

#### >Inbox </a><span class="unrd">(1)</span></td></tr><tr><td nowrap class="fld"><a name="lnkFldr" href=

#### >Inbox </a></td></tr><tr><td nowrap class="fld"><a name="lnkFldr" href=

unread=`$SED -n 's/.*>Inbox <\/a>\(<span class="unrd">(\([[:digit:]]\{1,\}\))<\/span>\|\)<\/td><\/tr><tr><td nowrap class="[^"]*"><a name="[^"]*".*/Inbox has \2 unread messages/;/Inbox has [[:digit:]]\{1,\} unread messages/p;s/Inbox has  /Inbox has 0 /p' /tmp/$$_results`
invalid_pass=`$SED -n 's/.*The user name or password you entered isn'"'"'t correct\. Try entering it again\..*/INVALID PASSWORD/p' /tmp/$$_results`

rm -f /tmp/$$*

if [ "$invalid_pass" == "INVALID PASSWORD" ]; then
	echo "$name: Login failed. Invalid Password."
	exit $CRITICAL
elif [ "$unread" == "" ]; then
	echo "$name: Could not determine the number of unread messages. Might need to update the script"
	exit $UNKNOWN
fi

echo "Login to $url successful: $unread"
exit $OK
