#!/bin/bash

# NAGIOS' wanted return values
NAG_OK=0;
NAG_WARN=1;
NAG_CRIT=2;
NAG_UNKNOWN=3;

# default value for proxy
if [ -z $1 ]; then
	HTTP_PROXY=http://localhost:8123
else
	HTTP_PROXY=$1
fi

# encure total execution time of script is below 60 seconds (the default timeout in nagios)
TIMEOUT_DIRECT=5
TIMEOUT_PROXY=20


# get real external IP adress
IP_WITHOUT_PROXY=`wget -q -O- --timeout=$TIMEOUT_DIRECT --tries=1 http://checkip.dyndns.com | grep -Eo "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+"`

# check if download worked
if [ $? -ne 0 ]; then
	echo "Failed to get external IP due to application error"
	exit $NAG_UNKNOWN
fi

# check if IP could be extracted
if [ -z $IP_WITHOUT_PROXY ]; then 
	echo "Failed to get external IP due to uninterpretable return from server:" $(wget -q -O- http://checkip.dyndns.com)
	exit $NAG_UNKNOWN
fi


IP_WITH_PROXY=`wget -q -O- --timeout=$TIMEOUT_PROXY --tries=1 --proxy --execute=http_proxy=$HTTP_PROXY http://checkip.dyndns.com | grep -Eo "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+"`

# check if download worked
if [ $? -ne 0 ]; then
	echo "Failed to get proxied IP"
	exit $NAG_UNKNOWN
fi

# check if IP could be extracted
if [ -z $IP_WITH_PROXY ]; then 
	echo "Failed to get external IP due to uninterpretable return from server:" $(wget -q -O- http://checkip.dyndns.com)
	exit $NAG_UNKNOWN
fi

# compare real IP to proxied IP
if [ $IP_WITH_PROXY == $IP_WITHOUT_PROXY ]; then
	echo "Your IP $IP_WITH_PROXY is currently not camouflaged!"
	exit $NAG_CRIT
else
	echo "Real IP $IP_WITHOUT_PROXY vs. fake IP $IP_WITH_PROXY. Your IP is hidden."
	exit $NAG_OK
fi
