#!/bin/sh
#
# $Id$

# PROVIDE: lighttpd_farm
# REQUIRE: DAEMON
# KEYWORD: shutdown

# Add the following lines to /etc/rc.conf to enable lighttpd_farm:
#
# lighttpd_farm_enable="NO"		# set to YES to enable lighttpd_farm
# lighttpd_farm_user="(user)"		# set username for running lighttpd_farm
# lighttpd_farm_program="(path)"	# set full path to lighttpd_farm program
# lighttpd_farm_root="(path)"		# set full path to root of lighttpd_farm
#

# TODO Valid status command

. /etc/rc.subr

name="lighttpd_farm"
rcvar=`set_rcvar`

load_rc_config $name

: ${lighttpd_farm_enable="NO"}
: ${lighttpd_farm_user="www"}
: ${lighttpd_farm_program="/usr/local/sbin/lighttpd"}
: ${lighttpd_farm_root="/usr/local/www"}

lighttpd_farm_conf_sfx="lighttpd.conf"
lighttpd_farm_pid_sfx="var/lighttpd.pid"

command="/usr/local/sbin/lighttpd"

start_cmd="lighttpd_farm_start"
stop_cmd="lighttpd_farm_stop"

lighttpd_farm_start_server()
{
	local _server _server_name _conf _pidfile _command_args
	local _pidcmd _rc_pid _doit

	_server="$1"
	_server_name=$(basename $_server)
	_conf="${_server}/${lighttpd_farm_conf_sfx}"
	_pidfile="${_server}/${lighttpd_farm_pid_sfx}"
	_command_args="-f ${_conf}"

	_rc_pid=
	_pidcmd='_rc_pid=$(check_pidfile '"$_pidfile $_procname"')'

	eval $_pidcmd

	if [ -z "$rc_fast" -a -n "$_rc_pid" ]; then
		echo 1>&2 "${name}:${_server_name} already running? (pid=$_rc_pid)."
		return 1
	fi

	echo -n " ${_server_name}"

	_doit="$command $rc_flags $_command_args"

	if [ -n "$_user" ]; then
		_doit="su - $_user -c 'sh -c \"$_doit\"'"
	fi

	_run_rc_doit "$_doit" || return 1
}

lighttpd_farm_stop_server()
{
	local _server _server_name _pidfile
	local _pidcmd _rc_pid _doit

	_server="$1"
	_server_name=$(basename $_server)
	_pidfile="${_server}/${lighttpd_farm_pid_sfx}"

	_rc_pid=
	_pidcmd='_rc_pid=$(check_pidfile '"$_pidfile $_procname"')'

	eval $_pidcmd

	if [ -z "$_rc_pid" ]; then
		[ -n "$rc_fast" ] && return 0
		echo 1>&2 "${name}:${_server_name} not running? (check $_pidfile)."
		return 1
	fi

	echo -n " ${_server_name}"

	_doit="kill -${sig_stop:-TERM} ${_rc_pid}"

	if [ -n "$_user" ]; then
		_doit="su - $_user -c 'sh -c \"$_doit\"'"
	fi

	_run_rc_doit "$_doit" || return 1

	_farm_pids="${_farm_pids}${_farm_pids:+ }${_rc_pid}"
}

lighttpd_farm_start()
{
	local _server

	echo -n "Starting ${name}:"
	for _server in $(find $lighttpd_farm_root -depth 1); do
		lighttpd_farm_start_server $_server || return 1
	done
	echo "."
}

lighttpd_farm_stop()
{
	local _server _farm_pids

	_farm_pids=

	echo -n "Stopping ${name}:"
	for _server in $(find $lighttpd_farm_root -depth 1); do
		lighttpd_farm_stop_server $_server || return 1
	done
	echo "."

	wait_for_pids $_farm_pids
}

run_rc_command "$1"
