#!/bin/sh
#
# cherokee      Cherokee HTTP server.
#
# chkconfig: 345 90 10
# description:	Cherokee HTTP server.
# processname: cherokee
# config: /etc/cherokee/cherokee.conf
# pidfile: /var/run/cherokee/cherokee.pid

# Do not load RH compatibility interface.
WITHOUT_RC_COMPAT=1

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

PIDFILE=/var/run/cherokee/cherokee.pid
LOCKFILE=/var/lock/subsys/cherokee
DAEMON=/usr/sbin/cherokee
RETVAL=0
USER=root
PORT=80

if test -r /etc/cherokee/cherokee.conf; then
	CONF_USER=`awk '/^[[:space:]]*User[[:space:]]/ {print $2}' /etc/cherokee/cherokee.conf`
	CONF_PORT=`awk '/^[[:space:]]*Port[[:space:]]/ {print $2}' /etc/cherokee/cherokee.conf`
fi
test -n "$CONF_USER" && USER=$CONF_USER
test -n "$CONF_PORT" && PORT=$CONF_PORT

#echo "user: $USER port: $PORT"

#	fix file ownership for unprivilegged user
for file in /var/log/cherokee/access.log \
	    /var/log/cherokee/error.log \
	    /var/run/cherokee/cherokee.pid; do
	test -f $file && chown $USER $file;
done


start()
{
	start_daemon --pidfile "$PIDFILE" --lockfile "$LOCKFILE" --expect-user "$USER" -- $DAEMON -b
	RETVAL=$?
	return $RETVAL
}

stop()
{
	stop_daemon --pidfile "$PIDFILE" --lockfile "$LOCKFILE" --expect-user "$USER" -- $DAEMON
	RETVAL=$?
	return $RETVAL
}

restart()
{
	stop
	start
}

reload()
{
	if test "$USER" != "root" -a $PORT -lt 1024; then
		echo "User $USER can't bind to port $PORT (< 1024). Use restart instead."
		msg_reloading cherokee
		failure "User $USER can't bind to port $PORT (< 1024). Use restart instead. Reloading"
		RETVAL=$?
		echo
		return $RETVAL
	fi

	msg_reloading cherokee
	stop_daemon --pidfile "$PIDFILE" --expect-user "$USER" -HUP -- $DAEMON
	RETVAL=$?
	return $RETVAL
} 

# See how we were called.
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	reload)
		reload
		;;
	restart)
		restart
		;;
	condstop)
		if [ -e "$LOCKFILE" ]; then
			stop
		fi
		;;
	condrestart)
		if [ -e "$LOCKFILE" ]; then
			restart
		fi
		;;
	condreload)
		if [ -e "$LOCKFILE" ]; then
			reload
		fi
		;;
	status)
		status --pidfile "$PIDFILE" --expect-user "$USER" -- $DAEMON
		RETVAL=$?
		;;
	*)
		msg_usage "${0##*/} {start|stop|reload|restart|condstop|condrestart|condreload|status}"
		RETVAL=1
esac

exit $RETVAL
