#! /bin/sh
#
# Start/stop Yaws web server
#
# Written by Miquel van Smoorenburg <miquels@cistron.nl>.
# Modified for Debian by Ian Murdock <imurdock@gnu.ai.mit.edu>.
# Modified for yaws #by Will Newton <will@debian.org>
# and Sergei Golovan <sgolovan@nes.ru>

### BEGIN INIT INFO
# Provides:          yaws
# Required-Start:    $remote_fs $network
# Required-Stop:     $remote_fs $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Starts Yaws web server
# Description:       Starts Yaws web server, a high perfomance
#                    HTTP 1.1 webserver written in Erlang.
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/yaws
NAME=yaws
DESC="Yaws web server"
YAWS_USER=yaws
YAWS_ID=debian_yaws
YAWS_CONF=/etc/yaws/yaws.conf

test -x $DAEMON || exit 0

# Include yaws defaults if available
if [ -f /etc/default/yaws ] ; then
    . /etc/default/yaws
fi

YAWS_HOME=$(sh -c "echo ~$YAWS_USER")

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions

control()
{
    HOME="$YAWS_HOME" $DAEMON --id $YAWS_ID $@
}

start()
{
    HOME="$YAWS_HOME" start-stop-daemon --quiet \
					--user $YAWS_USER \
					--chuid $YAWS_USER \
					--chdir $YAWS_HOME \
					--exec $DAEMON \
					--start \
					-- \
                                        --conf $YAWS_CONF \
					--id $YAWS_ID \
					--daemon $DAEMON_OPTS
    cnt=0
    while ! (control --status >/dev/null || test $? = 3) ; do
	log_progress_msg .
	cnt=`expr $cnt + 1`
	if [ $cnt -ge 10 ] ; then
	    return 1
	fi
	sleep 1
    done
    return 0
}

stop()
{
    control --stop >/dev/null || test $? = 3

    cnt=0
    while ! (control --status >/dev/null || test $? = 3) ; do
	log_progress_msg .
	cnt=`expr $cnt + 1`
	if [ $cnt -ge 10 ] ; then
	    return 1
	fi
	sleep 1
    done
    return 0
}

case "$1" in
    start)
	log_daemon_msg "Starting $DESC" "$NAME"
	start
	log_end_msg $?
    ;;
    stop)
	log_daemon_msg "Stopping $DESC" "$NAME"
	stop
	log_end_msg $?
    ;;
    status)
	control --status
    ;;
    reload|force-reload)
	log_daemon_msg "Reloading $DESC config" "$NAME"
	control --hup >/dev/null && log_end_msg 0 || log_end_msg 1
    ;;
    restart)
	log_daemon_msg "Restarting $DESC" "$NAME"
	stop
	start
	log_end_msg $?
    ;;
    *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|status|restart|reload|force-reload}" >&2
	exit 1
    ;;
esac

exit 0
