#!/bin/sh
VERSION="$(basename $0) Ver 1.0"
USAGE="Usage: $(basename $0) app_name command"
APP=
SDKDIR="/etc/sdk"
OPTIONS=

if [ $# -eq 0 ]; then
   echo "${USAGE}" >&2
   exit 1
fi
cd /
while [ $# -gt 0 ]; do
  case "${1}" in
    --help | -h | --h* )
       echo "${USAGE}" >&2
       exit 0
       ;;
    --version | -V )
       echo "${VERSION}" >&2
       exit 0
       ;;
    config_apply)
       cd ${SDKDIR}
       for APP in * ; do
         if [ -x "${SDKDIR}/${APP}" ]; then
           if [ $(uci check ${APP}) = "changed" ]; then
             uci refresh ${APP}
             "${SDKDIR}/${APP}" restart
           fi
         fi
       done
       exit 0
       ;;
    *)
       if [ -z "${APP}" ]; then
         APP="${1}"
       else
         OPTIONS="${OPTIONS} ${1}"
       fi
       shift
       ;;
   esac
done

is_rosp_deb=`echo ${APP} |grep "^rosp-" |wc -l`
if [ "${is_rosp_deb}" = "1" ];then
    EXT_APP=`echo ${APP}|sed "s/^rosp-//g"`
fi

RENAME_APP=`echo ${APP}|sed "s/-/_/g"`

if [ ${APP} = "all" ]; then
  cd ${SDKDIR}
  for APP in * ; do
    if [ -x "${SDKDIR}/${APP}" ]; then
      "${SDKDIR}/${APP}" ${OPTIONS}
    fi
  done
elif [ -f "${SDKDIR}/${APP}" ]; then
   "${SDKDIR}/${APP}" ${OPTIONS}
elif [ -f "${SDKDIR}/${EXT_APP}" ]; then
   "${SDKDIR}/${EXT_APP}" ${OPTIONS}
else
   if [ "${APP}" = "rosp-core" ];then
       pidof -o %PPID keeper >/dev/null 2>&1
       RETVAL=$?
       if [ "$RETVAL" = "0" ];then
            exit 0
       else
            exit 1
       fi
   fi
   dpkg_status=`dpkg -s ${APP} 2>/dev/null |grep   "^Status: install ok installed" |wc -l`
   if [ "${dpkg_status}" = "1" ]; then
       if [ -f "${SDKDIR}/${RENAME_APP}" ]; then
           "${SDKDIR}/${RENAME_APP}" ${OPTIONS}
       else
           exit 0
       fi
   else
       echo "${APP}: unrecognized app"  >&2
       exit 1
   fi
fi
exit $?
