#!/bin/sh

. /etc/image_features

_HOSTS=""
_URLS=""
_IPS=""
_EV_APP=""
_EV_NAME=""
_EV_TEXT=""
_EV_HREF=""
_EV_HREF_TEXT=""
_OUT=""
_OUT_END=""
_FORMAT="text"
_LINE_END="."
_LINE_BEGIN="   "
_VERBOSE=0

if [ $HW_TYPE == HW_TYPE_PC ]; then
    #_DEVS="lan0 lan1"
	_DEVS="lan0"
    _DNS_CONF="/etc/resolv.conf"
else
    _DEVS="wan0 lan0"
    _DNS_CONF="/etc/fixedforward.conf.mgmt"
fi

usage ()
{
    echo -e "usage: $0\t[--devs eth devices to test (default:lan0)] [--hosts hosts to test] [--urls URLs to test] [--ips ip address to test]"
    echo -e "\t[--eventapp application name] [--eventname event name] [--eventtext event text before status] [--eventhref event http reference] [--eventhreftext event http reference text]"
	echo -e "\t[--format html/text (default html)]"
	echo -e "\t[--verbose 0/1 (default 0)]"
}

while [ "$1" != "" ]; do
    case $1 in
        --hosts )          shift
                                _HOSTS="$1"
                                ;;
        --urls )       shift
                                _URLS="$1"
                                ;;
        --ips )         shift
                                _IPS="$1"
                                ;;
        --eventapp )     shift
                                _EV_APP="$1"
                                ;;
        --eventname )    shift
                                _EV_NAME="$1"
                                ;;
        --eventtext )    shift
                                _EV_TEXT="$1"
                                ;;
        --eventhref )    shift
                                _EV_HREF="$1"
                                ;;
        --eventhreftext ) shift
                                _EV_HREF_TEXT="$1"
                                ;;
        --format )    shift
                                _FORMAT="$1"
                                ;;
        --verbose )    shift
                                _VERBOSE="$1"
                                ;;
		--help )         shift
                                usage
                                exit 0
                                ;;
    esac
    shift
done

if [ $_VERBOSE -eq 0 ]; then
	exec  2>&1 > /dev/null
fi

if [ "$_FORMAT" == "html" ]; then
	_OUT="<span>"
	_OUT_END="</span>"
	_LINE_END="<br>"
fi
	
is_ip6()
{
	regex='^([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4}$'
	var="$1"

	if [[ $var =~ $regex ]]; then
	    return 1
	fi

	return 0
}

test_eth()
{
	[ $_VERBOSE -gt 0 ] && echo "test_eth $1"

    exists=$(ip link | awk -F: '$0 !~ "lo|vir|wl|^[^0-9]"{print $2;getline}' | grep $1)
    if [ ! -z $exists ]; then
		status=$(ethtool $1 | grep "Link detected" |  tr -d '\t')
		status=$(echo $status | awk '{print $3}')
		if [ "$status" == "yes" ]; then
			return 0
		else
			_OUT=$_OUT$(echo -e "$_LINE_BEGIN" $1 "link not detected"$_LINE_END)
		fi
    fi
    return 1
}

test_carrier()
{
	[ $_VERBOSE -gt 0 ] && echo "test_ip $1"

    for interface in $(ls /sys/class/net/ | grep -v lo);
	do
	    if [[ $(cat /sys/class/net/$interface/carrier) = 1 ]]; then OnLine=1; fi
	done
    # if ! [ $OnLine ]; then _OUT=$_OUT$(echo -e "$_LINE_BEGIN""Carrier is not online"$_LINE_END); return 1 ; else _OUT=$_OUT$(echo -e "$_LINE_BEGIN""Carrier is online"$_LINE_END); return 0 ; fi
	if ! [ $OnLine ]; then _OUT=$_OUT$(echo -e "$_LINE_BEGIN""Carrier is not online"$_LINE_END); return 1 ;fi
}

test_ip()
{
	[ $_VERBOSE -gt 0 ] && echo "test_ip $1"

	cmd=ping
	is_ip6 $1
	if [ $? -eq 1 ]; then
		cmd=ping6
	fi
    if [[ "$($cmd -c 1 $1 | grep '100% packet loss' )" != "" ]]; then
		_OUT=$_OUT$(echo -e "$_LINE_BEGIN""$1 is not reachable"$_LINE_END)
		return 0
    #else
		#_OUT=$_OUT$(echo -e "$_LINE_BEGIN""$1 is reachable"$_LINE_END)
	fi
    return 1
}

ping_gw()
{
	GW=$(ip r | grep default | cut -d ' ' -f 3)
	[ $_VERBOSE -gt 0 ] && echo "ping_gw $GW"
	ping -q -w 1 -c 1 $GW  && return 0 || _OUT=$_OUT$(echo -e "$_LINE_BEGIN""ping to gw ($GW) error"$_LINE_END); return 1
}

test_dns()
{
	[ $_VERBOSE -gt 0 ] && echo "test_dns $1"
	res=1
	ns=$(cat $_DNS_CONF  | grep -v '^#' | grep nameserver | awk '{print $2}')
	for i in $ns; do
		 py_cmd="(lambda __print, __g: [[[[(lambda __after: (__print('ok'), __after())[1] if (r == 0) else (__print('Error'), __after())[1])(lambda: (s.close(), None)[1]) for __g['r'] in [(s.connect_ex(location))]][0] for __g['location'] in [(('${i}', 53))]][0] for __g['s'] in [(socket.socket(socket.AF_INET, socket.SOCK_STREAM))]][0] for __g['socket'] in [(__import__('socket', __g, __g))]][0])(__import__('__builtin__', level=0).__dict__['print'], globals())"
		 res=$( python2 -c "$py_cmd" )
		 if [ "$res" == "Error" ]; then
			_OUT=$_OUT$(echo -e "$_LINE_BEGIN""DNS $i failed"$_LINE_END);
			res=1
		else 
			res=0
		fi
	done
	return $res
}

test_url()
{
	[ $_VERBOSE -gt 0 ] && echo "test_url $1"

    curl --silent -k $1 
    if [ "$?" != "0" ]; then
		_OUT=$_OUT$(echo -e "$_LINE_BEGIN""URL is not reachable"$_LINE_END);
    #else
		#_OUT=$_OUT$(echo -e "$_LINE_BEGIN""$1 is reachable"$_LINE_END);
    fi
}

test_host()
{
	[ $_VERBOSE -gt 0 ] && echo "test_host $1"

    c=$(command -v getent)
    if [ ! -z "$c" ]; then		
		$c hosts $1
		if [ "$?" != "0" ]; then
			_OUT=$_OUT$(echo -e "$_LINE_BEGIN""Host not reachable"$_LINE_END);
		#else
		#	_OUT=$_OUT$(echo -e "$_LINE_BEGIN""$1 is reachable"$_LINE_END);
		fi
    fi
}

####################################################################

status=1

main()
{
	for i in $_DEVS; do
		ret=1
		test_eth $i
		ret=$?
		if [ "$ret" == "0" ]; then
			status=0
		fi
	done

	if [ "$status" == "0" ]; then
		test_carrier
		if [ "$?" != "0" ]; then
			status=1
			if [ "$FEATURE_CLOUD_IPPBX_OWN_SERVICE" == "1" ]; then
				/etc/init.d/epnetwork restart
			else
				status=0
			fi
		fi

		if [ "$status" == "0" ]; then
			ping_gw
			if [ "$?" != "0" ]; then
				status=1
				if [ "$FEATURE_CLOUD_IPPBX_OWN_SERVICE" == "1" ]; then
					/etc/init.d/epnetwork restart
				else
					status=0
				fi
			fi

		if [ "$status" == "0" ]; then

			for i in $_IPS; do
				test_ip $i
				if [ "$?" != "0" ]; then
					status=1
				fi
			done

			dnsstatus=0
			if [ $HW_TYPE == HW_TYPE_PC ]; then
				test_dns
				if [ "$?" != "0" ]; then
					status=1
					dnsstatus=1
				fi
			fi

			if [ $dnsstatus == 0 ]; then
				for i in $_HOSTS; do
					test_host $i
					if [ "$?" != "0" ]; then
						status=1
					fi
				done

				for i in $_URLS; do
					test_url $i
					if [ "$?" != "0" ]; then
						status=1
					fi
				done
				fi
			fi
		fi
	fi

	text=$(echo $_EV_TEXT$_LINE_END$_OUT)

	[ $_VERBOSE -gt 0 ] && echo $text

	if [ ! -z "$_EV_APP" ] && [ ! -z "$_EV_NAME" ]; then
		/bin/raise_event -a "$_EV_APP" -n "$_EV_NAME" -t "$text" -h "$_EV_HREF" -r "$_EV_HREF_TEXT"
	fi

	[ "$status" == "0" ] && exit 0
	exit 1
}
####################################################################

main
