#!/bin/sh

. ../common/ajax_common


today_chart_dump()
{
	[ "${CGI_hours}" = "" ] && CGI_hours=24
	[ "${CGI_tmend}" = "" ] && CGI_tmend=`date +%s`

	${FLOWEYE} chart dump json=1 hours=${CGI_hours} tmend=${CGI_tmend} ${CGI_tags}
}


load_chart_timesum()
{
	[ "${CGI_time}" = "" ] && CGI_time=`date +%Y%m`

	#day daysecs min avg max
	${FLOWEYE} chart timesum tag=${CGI_tag} time=${CGI_time} | awk \
	'BEGIN{
		dot = "";
		printf "[";	
	}{
		col = 1;

		printf "%s", dot;
		printf "{";
		printf "\"day\":\"%s\",", $(col++);
		printf "\"secs\":\"%s\",", $(col++) +86400;
		printf "\"min\":\"%s\",", $(col++);
		printf "\"avg\":\"%s\",", $(col++);
		printf "\"max\":\"%s\"", $(col++);
		printf "}";
		if (dot == "") dot = ",";
	}END{
		printf "]";
	}'
}


history_chart_dump()
{
	tags=""

	for tag in `echo ${CGI_tags} | tr "|" " "`
	do
		tags="${tags} tag=${tag}"
	done

	[ "${CGI_showmax}" = "1" ] && tags="${tags} showmax=1"
	
	if [ "${CGI_types}" = "3day" ]; then
		hours=24
		tmend1=`date +%s`
		tmend2=$((${tmend1} - ( 60 * 60 * 24 ) ))
		tmend3=$((${tmend1} - ( 60 * 60 * 48 ) ))

		printf "["
		printf "`${FLOWEYE} chart dump json=1 hours=${hours} tmend=${tmend1} ${tags}`,"
		printf "`${FLOWEYE} chart dump json=1 hours=${hours} tmend=${tmend2} ${tags}`,"
		printf "`${FLOWEYE} chart dump json=1 hours=${hours} tmend=${tmend3} ${tags}`"
		printf "]"
	else
		tmend=`date +%s`
		hours1=24
		hours2=$((24*7))
		hours3=$((24*30))

		printf "["
		printf "`${FLOWEYE} chart dump json=1 hours=${hours1} tmend=${tmend} ${tags}`,"
		printf "`${FLOWEYE} chart dump json=1 hours=${hours2} tmend=${tmend} ${tags}`,"
		printf "`${FLOWEYE} chart dump json=1 hours=${hours3} tmend=${tmend} ${tags}`"
		printf "]"
	fi
}


case "${CGI_action}" in
	"chart_dump")
		retjson 0 "OK" "`today_chart_dump`"
		;;

	"load_chart_timesum")
		retjson 0 "OK" "`load_chart_timesum`"
		;;

	"history_chart_dump")
		retjson 0 "OK" "`history_chart_dump`"
		;;

	*)
		retjson 1 "UNKNOW_ACTION"
		;;
esac
