#!/bin/sh

. ../../common/ajax_common

npmhost_stat()
{
	${FLOWEYE} ntmhost stat | awk -F"=" \
	'BEGIN{
		dot="";
		printf "{";
	}{
		printf "%s", dot;
		printf "\"%s\":\"%s\"", $1, $2;
		if (dot == "") dot=",";
	}END{
		printf "}";
	}'
}


npmhost_set()
{
	${FLOWEYE} npmhost config enable=${CGI_enable}
	errmsg=`${FLOWEYE} ntmhost config enable=${CGI_enable}`

	if [ $? -ne 0 ]; then
		retjson 1 ${errmsg}
	else
		retjson 0 "ɹ"
	fi
}



topurl_list()
{
	case "${CGI_sort}" in
		"req_url")
			sortype="k1"
			;;
		"req_time")
			sortype="k2"
			;;
		"all_req")
			sortype="nk3"
			;;
		"dns_req")
			sortype="nk4"
			;;
		"https_req")
			sortype="nk5"
			;;
		"http_req")
			sortype="nk6"
			;;
		"http20x")
			sortype="nk7"
			;;
		"http30x")
			sortype="nk8"
			;;
		"http40x")
			sortype="nk9"
			;;
		"http50x")
			sortype="nk10"
			;;
		*)
			sortype="nk3"
	esac
	[ "${CGI_sortype}" = "desc" ] && sortype="r${sortype}"
	[ "${CGI_sortype}" = "" ] && sortype="rnk3"

	end=$(( ${CGI_page} * ${CGI_limit} ))
	start=$(( ${end} - ${CGI_limit} ))

	${FLOWEYE} hostinfo list | grep -i "${CGI_keyword}" | sort "-${sortype}" | awk \
	-v start=${start} -v end=${end} \
	'BEGIN{
		row = 0;
		dot = "";
		printf "{\"data\":[";
	}{
		if($1 !~ "^[a-zA-Z0-9\_|=@.-]+") next;

		row++;
		if( row > end  || row < start ) next;

		col = 1;
		printf "%s", dot;
		printf "{";
		printf "\"req_url\":\"%s\",", $(col++);
		printf "\"req_time\":\"%s\",", $(col++);
		printf "\"all_req\":\"%s\",", $(col++);
		printf "\"dns_req\":\"%s\",",$(col++);
		printf "\"https_req\":\"%s\",", $(col++);
		printf "\"http_req\":\"%s\",", $(col++);
		printf "\"http20x\":\"%s\",", $(col++);
		printf "\"http30x\":\"%s\",", $(col++);
		printf "\"http40x\":\"%s\",", $(col++);
		printf "\"http50x\":\"%s\"", $(col++);
		printf "}";

		if(dot == "") dot = ",";
	}END{
		printf "],\"total\":\"%s\"}", row;
	}'
}


case "${CGI_action}" in 
	"npmhost_stat")
		retjson 0 "OK" "`npmhost_stat`"
		;;
	
	"npmhost_set")
		action_check
		npmhost_set
		;;

	"topurl_list")
		retjson 0 "OK" "`topurl_list`"
		;;

	*)
		retjson 1 "UNKNOW_ACTION"
		;;
esac
