#!/bin/sh

# Athena�����ċN���X�N���v�g
#
#  [USAGE] ./start
#
#  ����Athena���N��������Ԃł͎��s���Ȃ��ʼn������B
#  �T�[�o�[�̏�Ԃ��m�F����X�N���v�g�����삷��̂ŁA�V�F���ɖ߂�܂���B
#  Athena���~�߂����Ƃ��� Ctrl+C �ŏI�����Ă��������B
#�@
#  �������� ./start & �Ƃ��ăo�b�N�O���E���h�ŋN�������
#  �V�F���ɖ߂��Ă��܂����A�T�[�o�[�̒�~�������ʓ|�ł��B

L_SRV=./bin/login-server
C_SRV=./bin/char-server
M_SRV=./bin/map-server

process_check() {
	# check login server
	if [ ! -f ${L_SRV}.pid ]; then
		login=0
	else
		login=`cat ${L_SRV}.pid`
		login=$(ps ax | grep "${L_SRV}" | grep "${login}" | wc -l)
	fi

	# check char server
	if [ ! -f ${C_SRV}.pid ]; then
		char=0
	else
		char=`cat ${C_SRV}.pid`
		char=$(ps ax | grep "${C_SRV}" | grep "${char}" | wc -l)
	fi

	# check map server
	if [ ! -f ${M_SRV}.pid ]; then
		map=0
	else
		map=`cat ${M_SRV}.pid`
		map=$(ps ax | grep "${M_SRV}" | grep "${map}" | wc -l)
	fi

	# echo "check: ${login} ${char} ${map}"
	echo `expr ${login} + ${char} + ${map}`
}

if [ `process_check` -ne 0 ]; then
	echo "Athena is already running..."
else
	./athena-start start
	sleep 30

	while true
	do
		if [ `process_check` -lt 3 ]; then
			printf "Error:"
			date
			sleep 10
			printf "Checking:"
			date
			if [ `process_check` -lt 3 ]; then
				printf "Error Confirmation:"
				date
				printf "Restoration:"
				date
				./athena-start restart
				else
				printf "Check Miss Sorry:"
				date
			fi
		#else
		#	printf "Check OK:"
		#	date
		fi
		sleep 10
	done
fi