#!/bin/bash

# string for help text
usage()
{
cat << EOF
usage:
This script reads index.html from check.torproject.org, which contains information wether or not tor is in your proxy-chain.
OPTIONS:
 -h	Show this message
 -H	hostname (default localhost)
 -p	proxy protocol (default socks5)
 -P	proxy port (default 9050)
 -v	verbose
EOF
}

# nagios expects one of these as return values
STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3
STATE_DEPENDENT=4

# set default parameters
PORT=9050
HOSTNAME="localhost"
PROTO="socks5"
VERBOSE=0

# override default values with input arguments
while getopts ":hH:p:P:v" OPTION
do
  case $OPTION in
	h) usage
	   exit $STATE_UNKNOWN; # nothing checked, but feasible input
	   ;;
	H) HOSTNAME=$OPTARG
	   ;;
	P) PORT=$OPTARG
	   ;;
	p) PROTO=$OPTARG
	   ;;
	v) VERBOSE=1;
	   ;;
	?) echo "unknown parameter" 
	   usage
	   exit $STATE_UNKNOWN;
 	   ;;
  esac
done                                

# download file
FILE=$(mktemp --tmpdir checktor_file.XXXX)
LOG=$(mktemp --tmpdir checktor_log.XXXX)
curl -s -x $PROTO://$HOSTNAME:$PORT check.torproject.org -o $FILE 2>&1 > $LOG

# check for the string "Sorry" in response
RESULT=$(html2text $FILE | head -n 1 | grep -e "Sorry" )
if [ $? -eq 0 ]; then
	echo "CRITICAL - $RESULT"
	rm $FILE
	rm $LOG
	exit $STATE_CRITICAL
fi

# check for the string "Congratulation" in response
RESULT=$(html2text $FILE | head -n 1 | grep -e "Congratulation" )
if [ $? -eq 0 ]; then
	echo "OK - $RESULT" 
	rm $FILE
	rm $LOG
	exit $STATE_OK
fi

echo "UNKNOWN - neither positive nor negative response; check url"
rm $FILE
rm $LOG
exit $STATE_UNKNOWN

