#!/bin/sh

. ../../common/ajax_common

TCPPING="/usr/ramdisk/app/ping/tcpping"


if [ "${CGI_proxy}" = "0" ]; then
	if [ "${CGI_type}" = "icmp" ]; then
		if [ "`uname`" = "Linux" ]; then
			errmsg=`ping -c 1 -W 1 ${CGI_ip} | grep -v PING | grep bytes`
		else
			errmsg=`ping -o -t 1 ${CGI_ip} | grep -v PING | grep bytes`
		fi
		timer=`echo ${errmsg} | grep icmp | cut -d" " -f7 | awk -F "=" '{t=sprintf("%.2f", $2);print t}'`
		ttl=`echo ${errmsg} | grep icmp | cut -d" " -f6 | cut -d"=" -f2`
	else
		print_json_head
		${TCPPING} ${CGI_ip} ${CGI_port}
		exit 0
	fi
else
	CGI_proxy=`echo ${CGI_proxy} | cut -d"-" -f2`
	cmdargs="if=${CGI_proxy} ip=${CGI_ip}"
	if [ "${CGI_nexthop}" != "" ]; then
		cmdargs="${cmdargs} nexthop=${CGI_nexthop}"
	fi
	errmsg=`${FLOWEYE} ping ${cmdargs} count=1`
	timer=`echo ${errmsg} | cut -d" " -f6 | cut -d"=" -f2 | sed 's/ms//g' | awk '{t=sprintf("%.2f", $1);print t}'`
	ttl=`echo ${errmsg} | cut -d" " -f5 | cut -d"=" -f2`
fi


if [ "${errmsg}" = "" ]; then
	retjson 1 "NO Reply from ${CGI_ip}"
elif [  "${timer}" = "0.00" -o "${timer}" = "" ]; then
	retjson 1 "${errmsg}"
else
	retjson 0 "OK" "{\"timer\":${timer}, \"ttl\":${ttl}}"
fi
