#!/bin/sh
#
# lighttpd	lighttpd Web Server
#
# chkconfig:	345 85 15
# description:	lighttpd is a World Wide Web server.  It is used to serve \
#		HTML files and CGI.
#

# Source function library
. /etc/rc.d/init.d/functions

# Get network config
. /etc/sysconfig/network

# Get service config
[ -f /etc/sysconfig/lighttpd ] && . /etc/sysconfig/lighttpd

# Check that networking is up.
if is_yes "${NETWORKING}"; then
	if [ ! -f /var/lock/subsys/network -a "$1" != stop -a "$1" != status ]; then
		msg_network_down "Lighttpd Web Server"
		exit 1
	fi
else
	exit 0
fi

configtest() {
	out=$(env SHELL=/bin/sh lighttpd -t -f /etc/lighttpd/lighttpd.conf $HTTPD_OPTS 2>&1)
	rc=$?
	if [ "$rc" = 0 ]; then
		return
	fi
	echo >&2 ""
	echo >&2 "$out"
	fail
}

start() {
	env SHELL=/bin/sh lighttpd -f /etc/lighttpd/lighttpd.conf $HTTPD_OPTS
	RETVAL=$?
	if [ $RETVAL -eq 0 ]; then
		ok
	   	touch /var/lock/subsys/lighttpd
	else
		fail
	fi
	return $RETVAL
}

stop() {
	killproc --pidfile /var/run/lighttpd.pid lighttpd
	rm -f /var/lock/subsys/lighttpd >/dev/null 2>&1
}

reload() {
	# sending INT signal will make lighttpd close all listening sockets and
	# wait for client connections to terminate.
	killproc --pidfile /var/run/lighttpd.pid lighttpd -INT
	env SHELL=/bin/sh lighttpd -f /etc/lighttpd/lighttpd.conf $HTTPD_OPTS
}

RETVAL=0
# See how we were called.
case "$1" in
  start)
	# Check if the service is already running?
	if [ ! -f /var/lock/subsys/lighttpd ]; then
		msg_starting "Lighttpd Web Server"
		configtest || exit 1
		start
	else
		msg_already_running "Lighttpd Web Server"
	fi
	;;
  stop)
	# Stop daemons.
	if [ -f /var/lock/subsys/lighttpd ]; then
		msg_stopping "Lighttpd Web Server"
		stop
	else
		msg_not_running "Lighttpd Web Server"
	fi
	;;
  status)
	status lighttpd
	RETVAL=$?
	;;
  restart)
	if [ -f /var/lock/subsys/lighttpd ]; then
		configtest || exit 1

		# short circuit to safe reload if pid exists and is alive
		pid=$(pidofproc lighttpd lighttpd.pid)
		if [ "$pid" ] && checkpid $pid; then
			msg_reloading "Lighttpd Web Server"
			reload
		else
			msg_stopping "Lighttpd Web Server"
			stop
			msg_starting "Lighttpd Web Server"
			start
		fi
		RETVAL=$?
	else
		msg_not_running "Lighttpd Web Server"
		msg_starting "Lighttpd Web Server"
		start
	fi
	;;
  reload|graceful|force-reload)
	if [ -f /var/lock/subsys/lighttpd ]; then
		msg_reloading "Lighttpd Web Server"
		configtest || exit 1
		reload
		RETVAL=$?
	else
		msg_not_running "Lighttpd Web Server"
		RETVAL=7
	fi
	;;
  configtest)
		show "Checking lighttpd config syntax"
		configtest
		RETVAL=$?
		[ $RETVAL = 0 ] && ok || fail
	;;
  flush-logs)
	if [ -f /var/lock/subsys/lighttpd ]; then
		nls "Rotating %s logs" lighttpd
		killproc --pidfile /var/run/lighttpd.pid lighttpd -HUP
		RETVAL=$?
	else
		msg_not_running "Lighttpd Web Server"
		RETVAL=7
	fi
	;;
  *)
	msg_usage "$0 {start|stop|restart|reload|force-reload|graceful|configtest|flush-logs|status}"
	exit 3
	;;
esac

exit $RETVAL
