#!/bin/sh

. ../common/ajax_common

SYS_CHECK="${RAMDISK}/bin/ipe_sys_check"
TMP_DIR="${RAMDISK}/tmp/sys_check"


do_sys_check()
{
	${SYS_CHECK} >/dev/null 2>&1 &

	WEB_LOGGER "ϵͳ"
	retjson 0 "OK"
}


query_check_stat()
{
	exist=`ps -ax | grep "ipe_sys_check" | grep -v grep`

	if [ "${exist}" != "" ];then
		echo "RUN"
	else
		echo "DONE"
	fi
}


load_check_result()
{
	dot=""
	printf  "["

	for ctx in `ls ${TMP_DIR}/api/*.ok`
	do	
		printf "${dot}"
		cat ${ctx}
		rm ${ctx}
		
		[ "${dot}"="" ] && dot=","
	done  

	printf "]"
}


verify_sys_time()
{
	os=`uname`
	timefmt=`echo "${CGI_time}" | awk -v os=${os} \
	'{
		split($1, arg1, "-");
		split($2, arg2, ":");

		if(os == "Linux")
			printf "-s %s", $0;
		else
			printf arg1[1]arg1[2]arg1[3]arg2[1]arg2[2]"."arg2[3];
	}'`

	date "${timefmt}"

	WEB_LOGGER "޸ϵͳʱ"
	retjson 0 "ɹ"
}


restart_process()
{
	[ "${CGI_process}" = "" ] && retjson 1 "UNKNOW_PROCESS"

	${IPECTRL} stop ${CGI_process} >/dev/null 2>&1
	${IPECTRL} start ${CGI_process} >/dev/null 2>&1

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


case "${CGI_action}" in
	"do_sys_check")
		action_check
		do_sys_check
		;;

	"load_check_result")
		retjson 0 "`query_check_stat`"   "`load_check_result`"
		;;

	"verify_sys_time")
		action_check
		verify_sys_time
		;;

	"restart_process")
		action_check
		restart_process
		;;

	*)
		retjson 1 "UNKNOW_ACTION"
		;;
esac
