#!/bin/sh -e

# 
# kwebserver      Startup script for the KHOMP webserver daemon  
# 
# chkconfig: - 88 15 
# description: The KHOMP server manages communication between Asterisk and KHOMP telephony cards 



### BEGIN INIT INFO
# Provides:          kwebserver
# Required-Start:    $local_fs $network $syslog
# Required-Stop:     $local_fs $network $syslog
# Should-Start:      networking network-manager
# Should-Stop:       networking network-manager
# Default-Start:     2 3 5
# Default-Stop:      0 6
# Short-Description: provides the Kwebconfig service
### END INIT INFO


KHOMPBASE="/opt/khomp/webserver"
LIGHTTPD="${KHOMPBASE}/bin/lighttpd"

# Check needed files.
test -x ${LIGHTTPD}        || \
{
    echo "ERROR: Unable to find lighttpd! Not starting!" >&2
    exit 1
}

lighttpd_helpline="Supported actions: start|stop|restart|force-start|force-stop|status|help"


do_start() 
{
    if [ -f ${KHOMPBASE}/skip-kwebserver ]
    then
        echo "+ File ${KHOMPBASE}/skip-kwebserver exists: skipping kwebserver initialization."
        return 1
    fi
    
    if ! (pidof "${LIGHTTPD}" 1> /dev/null 2>/dev/null)
    then
        echo "+ Starting kwebserver...."
        ${LIGHTTPD} -f ${KHOMPBASE}/conf/lighttpd-inc.conf
        return 0
    else
        echo "+ Service kwebserver already started, cannot start again."
        return 1
    fi
}

do_stop()
{
    pidnum=`pidof ${LIGHTTPD} || echo ""`

    if [ "w${pidnum}" != "w" ]
    then
        echo -n "+ Stopping kwebserver..."
        kill -TERM "${pidnum}" 1> /dev/null 2> /dev/null

        echo " done!"
        return 0
    else
        echo "+ Service kwebserver not running, cannot stop."
        return 1
    fi
}

do_status()
{
    if pidof ${LIGHTTPD} 1>/dev/null
    then
        echo "running"
        exit 0
    else
        echo "not running"
        exit 1
    fi
}

case "$1"
in
    start|force-start|"")
        do_start
    ;;

    stop|force-stop)
        do_stop
    ;;

    restart)
        do_stop
        sleep 5
        do_start
    ;;

    status)
        do_status
    ;;

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

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