#!/bin/sh

source /{{ EXEM_HOME }}/ndm/bin/reg.env
#source /root/test2/bin/reg.env



func_check_log_file()
{
	LOG_CHK_SIZE=1048576
	if [ -n "$2" ];then
		LOG_CHK_SIZE=$2
	fi

	if [ -f "$1" ];then

		LOG_SIZE=`ls -la $1 | awk -F' ' '{print $5}'`
		if [ $? -eq 0 ]; then

			if [ ${LOG_SIZE} -gt ${LOG_CHK_SIZE} ]; then
				rm -rf $1
#				echo "log size is over. remove log file.[size:${LOG_SIZE},file:$1]"
			fi

		fi

	fi

}

PROCESS_NAME="exem-ndm-agent"
PROCESS_PATH="${PROCESS_NAME}"
PID_FILE="ndm-agent.pid"

if [ ! -d "${EXEM_NDM_HOME}" ];then
	echo "exem ndm home directory is not exist.[${EXEM_NDM_HOME}]"
	exit 1
fi


# working directory is ${EXEM_NDM_HOME}/bin
cd ${EXEM_NDM_HOME} || exit 1


if [ -f "${EXEM_NDM_HOME}/data/${PID_FILE}" ]; then
	RUN_PID=`cat ${EXEM_NDM_HOME}/data/${PID_FILE} | tr '\0' '\n' || echo "none"`
else
	RUN_PID="none"
fi

PEAK=0

while :
do

	# log manage
	func_check_log_file "${EXEM_NDM_HOME}/log/svc.log" 1048576

	if [ "${RUN_PID}" = "none" ];then
		PATH=${EXEM_NDM_HOME}/bin:$PATH ${PROCESS_PATH} > /dev/null 2>&1 &
		RUN_PID="$!"
		echo "execute ${PROCESS_PATH} process.[${RUN_PID}]"
		sleep 3
	fi

	if [ ! "${RUN_PID}" = "none" ] && [ -f "/proc/${RUN_PID}/cmdline" ];then
		# PROC_COMM=`cat /proc/${RUN_PID}/comm || echo "none"`
		PROC_COMM=`cat /proc/${RUN_PID}/cmdline | tr '\0' ' ' | awk -F' ' '{print $1}' || echo "none"`
#		echo "PROC_COMM[${PROC_COMM}]"
	else
		PROC_COMM="none"
	fi


	if [ ! "${PROC_COMM}" = "${PROCESS_PATH}" ];then
		echo "${PROCESS_NAME} process is not running.[pid:${RUN_PID}],comm[${PROC_COMM}]"
		RUN_PID="none"
	fi

	##########################################
	# check memory peak
	CUR_DATE=`date +%d' '%H:%M:%S`

#	MONGOMON_PID=`ps -ef | grep -v grep | grep -v vi | grep -v tail | grep -v ctl | grep -v svc | grep ${PROCESS_NAME} | awk -F' ' '{print $2}'`
#	if [ -n "${MONGOMON_PID}" ];then



	if [ ! "${RUN_PID}" = "none" ];then

#		RESULT=`ps -p ${RUN_PID} -o user,pid,pcpu,pmem,rss,sz,size,vsize,cmd --no-heading`
		RESULT=`ps -p ${RUN_PID} -o user,pid,pcpu,pmem,rss,sz,size,vsize,cmd --no-heading`
		if [ -z "${RESULT}" ];then
			echo "${CUR_DATE} get process stat has failed.[${RUN_PID}]"
			PEAK=0
		fi

		RSS=`echo ${RESULT} | awk -F' ' '{print $5}'`
		if [ ${RSS} -gt ${PEAK} ];then
			OUT_PEAK="  PEAK:${PEAK}/${RSS}"
			PEAK=${RSS}
			PEAK_STAT="peak"
		else
			OUT_PEAK="  PEAK:${PEAK}"
			PEAK_STAT=""
		fi

#		echo "${CUR_DATE} ${RESULT}${OUT_PEAK}"

		if [ -n "${PEAK_STAT}" ];then
			func_check_log_file "peak.log" 1024
			echo "${CUR_DATE} ${RESULT}${OUT_PEAK}" >> peak.log
		fi

	else
		echo "${CUR_DATE} ${PROCESS_NAME} is not running."
		PEAK=0
	fi


	sleep 3
done



