#!/bin/sh
# chkconfig: 345 90 10
#
# apps
#
# start the applications here

# find the apps to run with regard to the name we have been called with
if [ $# -eq 2 ]; then
    shift
fi
scriptname=$(basename $0)
scriptname=${scriptname#[SK][0-9][0-9]}

. /etc/init.d/rc.config

case "$scriptname" in
    *apps)
        # app="httpd telnetd sntpd"
        apps="telnetd callctrl"
    ;;
    *)
        apps=${scriptname}
    ;;
esac


# set the names of the binaries and directories of the apps
cmd=""
for app in $apps; do
    case "$app" in
        *powermanager)
            cmd="$cmd ${app}_bin=PowerManager ${app}_dir=/sbin"
        ;;
        *callctrl)
            cmd="$cmd ${app}_bin=callctrl ${app}_dir=/bin"
        ;;
        *httpd)
            cmd="$cmd ${app}_bin=httpd ${app}_dir=/usr/sbin ${app}_arg=\"-h /webroot\""
        ;;
        *telnetd)
            cmd="$cmd ${app}_bin=telnetd ${app}_dir=/usr/sbin"
        ;;
        *)
            msg="Usage $0 {${apps// /|}} {start|stop}"
            echo $msg >&2
            exit 1
        ;;
    esac
done

# do the required action
case "$1" in
    start|"")
        # Start the binaries
        for app in $apps; do
            # append the command to start the corresponding application
            cmd="$cmd; \
            if [ -x \$${app}_dir/\$${app}_bin ]; then \
                ( trap \"\" HUP && exec \$${app}_dir/\$${app}_bin \${${app}_arg:-} ) & \
                sleep 1;
                if [ \$? -ne 0 ]; then \
                    echoerror \"Cannot execute \$${app}_dir/\$${app}_bin\"; \
                fi; \
            else \
                echoerror \"\$${app}_dir/\$${app}_bin does not exists or is not executable\"; \
            fi"
        done
        # start the applications
        eval "$cmd 2>&1 | tee /tmp/log.apps" &
    ;; 
    stop)
        cmd=":"
        for app in $apps; do
            # append the command to start the corresponding application
            cmd="$cmd; killall $app"
        done
        # start the applications
        eval "$cmd 2>&1 | tee /tmp/log.apps" &
    ;;
    *)
        echo "Usage $scriptname {start|stop}" >&2
        exit 1
    ;;
esac
