#!/bin/sh

. /etc/PG.conf

APPUIROOT="/usr/ramdisk/www/app"
APPROOT="${PGPATH}/app"

ui_action()
{
	cd ${APPROOT}
	
	mkdir -p ${APPUIROOT}
	
	case "$1" in
	"uistart")
		for appname in `ls`
		do
			if [ -e ${APPROOT}/${appname}/appctrl ]; then
				${APPROOT}/${appname}/appctrl uistart
				if [ $? != 0 ]; then
					echo "${appname} app uistart error!"
				fi
			fi
		done
		;;
		
	"uistop")
		;;
		
	"*")
		echo "Unknown action \"$1\""
	;;

	esac
}

app_action()
{
	target="$2"
	
	cd ${APPROOT}
	
	mkdir -p ${APPUIROOT}
	
	case "$1" in
	"start")
		if [ "${target}" = "all" ]; then
			for appname in `ls`
			do
				if [ -e ${APPROOT}/${appname}/appctrl ]; then
					${APPROOT}/${appname}/appctrl start
					if [ $? != 0 ]; then
						echo "${appname} app start error!"
					fi
					
				fi
			done
		else
			if [ -e ${APPROOT}/${target}/appctrl ]; then
				${APPROOT}/${target}/appctrl start
				if [ $? != 0 ]; then
					echo "${target} app appstart error!"
				fi
				
			fi
		fi
		return 0
		;;
		
	"stop")
		if [ "${target}" = "all" ]; then
			for appname in `ls`
			do
				if [ -e ${APPROOT}/${appname}/appctrl ]; then
					${APPROOT}/${appname}/appctrl stop >/dev/null 2>&1
					if [ $? != 0 ]; then
						echo "${appname} app stop error!"
					fi
					
				fi
			done
		else
			if [ -e ${APPROOT}/${target}/appctrl ]; then
				${APPROOT}/${target}/appctrl stop >/dev/null 2>&1
				if [ $? != 0 ]; then
					echo "${target} app stop error!"
				fi
			fi
		fi
		return 0
		;;

	"*")
		echo "Unknown action \"$1\""
		;;

	esac
}

wait_panaosup()
{
	local cnt=30

	while [ ${cnt} -gt 0 ]; do
		err=`/usr/ramdisk/bin/floweye system stat`
		[ "$?" = "0" ] && return 0
		sleep 1
		cnt=$((${cnt} - 1))
	done

	return 1
}

case "$1" in
"start")
	target="$2"
	if [ "${target}" = "" ]; then
		result=`wait_panaosup`
		if [ "$?" != "0" ]; then
			echo "panaos not started, exit!"
			exit 1
		fi
		target="all"
	fi

	app_action "start" "${target}"
	;;

"stop")
	target="$2"
	[ "${target}" = "" ] && target="all"
	app_action "stop" "${target}"
	;;

"uistart")
	result=`wait_panaosup`
	if [ "$?" != "0" ]; then
		echo "panaos not started, exit!"
		exit 1
	fi
	ui_action "uistart"
	;;

"uistop")
	ui_action "uistop"
	;;

esac
