#!/bin/sh

# 
# khomp-services      Startup script for the KHOMP services daemons 
# 
# chkconfig: - 88 15 
# description: The KHOMP server manages communication between Asterisk and KHOMP telephony cards 



### BEGIN INIT INFO
# Provides:          khomp
# Required-Start:    $local_fs $network
# Required-Stop:     $local_fs $network
# Should-Start:      networking network-manager
# Should-Stop:       networking network-manager
# Default-Start:     2 3 5
# Default-Stop:      0 6
# Short-Description: khomp daemons
### END INIT INFO

helpline="Supported actions: start|stop|restart|force-start|force-stop|reset-modules|status|help"

checkOnly()
{
    if [ ! -f /etc/init.d/$1 ]
    then
        return 1
    fi
    
    echo -n "$1: "
    
    /etc/init.d/$1 status 2>/dev/null

    return 0
}

checkAndStart()
{
    if [ ! -f /etc/init.d/$1 ]
    then
        return 1
    fi
        
    if (/etc/init.d/$1 status 2>/dev/null | grep -q "not")
    then
        /etc/init.d/$1 start
    else
        echo "$1 already running"
    fi

    return 0
}

checkAndStop()
{
    if [ ! -f /etc/init.d/$1 ]
    then
        return 1
    fi
        
    if (/etc/init.d/$1 status 2>/dev/null | grep -qv "not")
    then
        /etc/init.d/$1 stop
    else
        echo "$1 not running"
    fi
    
    return 0
}

resetModules()
{
    kwebhelper resetallmodules
    return 0
}

case "$1"
in
    start|force-start|"")
        checkAndStart "khompdrv"
        checkAndStart "klogserver"
        checkAndStart "kmpserver"
        checkAndStart "k3lserver"
        checkAndStart "kqueryserver"
        checkAndStart "kibs"
        checkAndStart "kgateway"
        checkAndStart "kwebserver"
    ;;
    
    stop|force-stop)
        checkAndStop "kwebserver"
        checkAndStop "kgateway"
        checkAndStop "kibs"
        checkAndStop "kqueryserver"
        checkAndStop "k3lserver"
        checkAndStop "kmpserver"
        checkAndStop "klogserver"
        sleep 5
        checkAndStop "khompdrv"
    ;;

    init)
        sleep 10
        $0 start
    ;;
    
    restart)
        $0 stop
        sleep 5
        $0 start
    ;;

    status)
        checkOnly "khompdrv"
        checkOnly "klogserver"
        checkOnly "kmpserver"
        checkOnly "k3lserver"
        checkOnly "kqueryserver"
        checkOnly "kibs"
        checkOnly "kgateway"
        checkOnly "kwebserver"
    ;;

    resetmodules)
        resetModules
    ;;

    reset-modules)
        resetModules
    ;;

    help)
        echo "${helpline}"
        exit 0
    ;;

    *)
        echo "ERROR: Unknown action! ${helpline}"
        exit 1
    ;;

esac

