#!/sbin/runscript
# Copyright 1999-2012 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header: /var/cvsroot/gentoo-x86/www-servers/uwsgi/files/uwsgi.initd,v 1.3 2012/08/27 08:34:07 ultrabug Exp $

PROGNAME=${SVCNAME#*.}

UWSGI_EXEC=/usr/bin/uwsgi
PIDPATH=/var/run/uwsgi
PIDFILE="${PIDPATH}/${PROGNAME}.pid"

extra_started_commands="reload"

depend() {
	need net
}

start() {
	local OPTIONS

	if [ "${SVCNAME}" = "uwsgi" ]; then
		eerror "You are not supposed to run this script directly. Create a symlink"
		eerror "for the FastCGI application you want to run as well as a copy of the"
		eerror "configuration file and modify it appropriately like so..."
		eerror
		eerror "  ln -s uwsgi /etc/init.d/uwsgi.trac"
		eerror "  cp /etc/conf.d/uwsgi /etc/conf.d/uwsgi.trac"
		eerror "  nano /etc/conf.d/uwsgi.trac"
		eerror
		return 1
	fi

	if [ -z "${UWSGI_SOCKET}" ]; then
		eerror "You need to specify path (or name) of UNIX/TCP socket to bind to"
		eerror "in UWSGI_SOCKET"
		return 1
	fi

	if [ -z "${UWSGI_PROGRAM}" ] && [ -z "${UWSGI_XML_CONFIG}" ]; then
		eerror "You need to specify which \$UWSGI_PROGRAM or \$UWSGI_XML_CONFIG"
		eerror "you want to start."
		eerror "Please adjust /etc/conf.d/uwsgi.${PROGNAME}"
		return 1
	fi

	if [ -n "${UWSGI_PROGRAM}" ] && [ -n "${UWSGI_XML_CONFIG}" ]; then
		eerror "Only one of the two may be defined:"
		eerror "  UWSGI_PROGRAM=${UWSGI_PROGRAM}"
		eerror "  UWSGI_XML_CONFIG=${UWSGI_XML_CONFIG}"
		return 1
	fi


	OPTIONS="--master --daemonize"

	if [ -n "$UWSGI_LOG_FILE" ]; then
		OPTIONS="${OPTIONS} $UWSGI_LOG_FILE"
	else
		OPTIONS="${OPTIONS} /dev/null --disable-logging"
	fi

	if [ "${UWSGI_THREADS}" = "1" ]; then
		OPTIONS="${OPTIONS} --enable-threads"
	fi

	if [ -n "${UWSGI_SOCKET}" ]; then
		OPTIONS="${OPTIONS} --socket ${UWSGI_SOCKET}"
	fi

	if [ -n "${UWSGI_CHILDREN}" ]; then
		OPTIONS="${OPTIONS} --processes ${UWSGI_CHILDREN}"
	fi

	if [ -n "${UWSGI_CHROOT}" ]; then
		OPTIONS="${OPTIONS} --chroot ${UWSGI_CHROOT}"
	fi

	[ -z "${UWSGI_DIR}" ] && UWSGI_DIR="/"
	[ -z "${UWSGI_USER}" ] && UWSGI_USER="root"

	if [ -n "${UWSGI_EXTRA_OPTIONS}" ]; then
		OPTIONS="${OPTIONS} ${UWSGI_EXTRA_OPTIONS}"
	fi

	if [ -n "${UWSGI_PROGRAM}" ]; then
		OPTIONS="${OPTIONS} --wsgi-file ${UWSGI_PROGRAM}"
	fi

	if [ -n "${UWSGI_XML_CONFIG}" ]; then
		OPTIONS="${OPTIONS} --xmlconfig ${UWSGI_XML_CONFIG}"
	fi

	ebegin "Starting uWSGI application ${PROGNAME}"
	cd "${UWSGI_DIR}" && \
	start-stop-daemon --start --user "${UWSGI_USER}" --exec "${UWSGI_EXEC}" -- ${OPTIONS} --pidfile "${PIDFILE}"
	eend $?
}

reload() {
	ebegin "Reloading ${SVCNAME}"
	kill -HUP `cat ${PIDFILE}` &>/dev/null
	eend $? "Failed to reload ${SVCNAME}"
}

stop() {
	ebegin "Stopping uWSGI application ${PROGNAME}"
	start-stop-daemon --stop --pidfile "${PIDFILE}" --signal 3
	eend $?
}