#!/bin/sh
_checkpid(){
	echo "###############################################################"
	echo "Check PID..."
	PIDFILE="/tmp/JXJSQ-service.pid"
	 
	if [ -s ${PIDFILE} ]; then
		SPID=`cat ${PIDFILE}`
		if [ -e /proc/${SPID}/status ]; then
			echo "The process $pname is already exists ! pid:$SPID."
			exit 1
		fi
		cat /dev/null > ${PIDFILE}
	fi
	echo $$ > ${PIDFILE}
}

initJXJSQ(){
	echo "######################################################"
	echo "initJXJSQ"
	chmod +x /usr/bin/JXJSQ
	uci get JXJSQ.@JXJSQ[0] >/dev/null 2>&1
	if [ "$?" != "0" ];then
		uci get JXJSQ
		if [ "$?" != "0" ];then
			touch /etc/config/JXJSQ
			uci add JXJSQ JXJSQ
			uci commit JXJSQ
		fi
	fi

	uci get JXJSQ.@JXJSQ[1] >/dev/null 2>&1
	if [ "$?" = "0" ];then
		uci del JXJSQ.@JXJSQ[1]
		uci del JXJSQ.@JXJSQ[1]
		uci del JXJSQ.@JXJSQ[1]
		uci commit JXJSQ
	fi
	version=$(opkg list-installed|grep jxjsq|awk '{print $3}')
	uci set JXJSQ.@JXJSQ[0].version=$version
	uci commit JXJSQ
}

checkuptime(){
	echo "######################################################"
	echo "checkuptime"
	/usr/bin/JXJSQ -u
}

checkrun(){
	echo "######################################################"
	echo "checkrun"	
	PIDFILE="/tmp/JXJSQ.pid"
	if [ -s ${PIDFILE} ]; then
		SPID=`cat ${PIDFILE}`
		if [ -e /proc/${SPID}/status ]; then
			echo "The process $pname is already exists ! pid:$SPID."
		else
			/usr/bin/JXJSQ start &
		fi
	else
		/usr/bin/JXJSQ start &
	fi
}

main(){
	echo "######################################################"
	echo "main"
	while true
	do
		checkrun
		checkuptime
		sleep 10
	done
}

startservice(){
	echo "######################################################"
	echo "startservice"
	checkpid
	initJXJSQ
	main
}

stopservice(){
	for servicepid in `cat /tmp/JXJSQ-service.pid`;do
		kill -9 $servicepid > /dev/null 2>&1
	done
	echo "JXJSQ-service has stopped!"
}

action=$1
[  -z $1 ] && action=start
case "$action" in
start)
    startservice
    ;;
stop)
    stopservice
    ;;
*)
    echo "
Usage: JXJSQ [<OPTIONS>]

Options:
        start
        stop
"
    ;;
esac
