#!/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
					if [ $? != 0 ]; then
						echo "${appname} app stop error!"
					fi
					
				fi
			done
		else
			if [ -e ${APPROOT}/${target}/appctrl ]; then
				${APPROOT}/${target}/appctrl stop
				if [ $? != 0 ]; then
					echo "${target} app stop error!"
				fi
			fi
		fi
		return 0
		;;
	"*")
		echo "Unknown action \"$1\""
		;;

	esac
}

case "$1" in
"start")
	target="$2"
	[ "${target}" = "" ] && target="all"
	app_action "start" "${target}"
	;;

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

"uistart")
	ui_action "uistart"
	;;

"uistop")
	ui_action "uistop"
	;;

esac
