#!/bin/sh
#
# Start PHP as a FastCGI daemon
# This script was installed via the Hiawatha package

USER=www-data
PORT=2345
FORKS=3

# ================================================

if [ "`id -un`" != "${USER}" ]; then
	sudo -u ${USER} $0 $1
	exit
fi

if [ -f /usr/local/bin/php-cgi ]; then
	PHPBIN=/usr/local/bin/php-cgi
elif [ -f /usr/bin/php-cgi ]; then
	PHPBIN=/usr/bin/php-cgi
else
	echo "Fatal error: php-cgi binary not found."
	exit
fi

start_fcgi_server() {
	export PHP_FCGI_CHILDREN=${FORKS}
	export PHP_FCGI_MAX_REQUESTS=500

	cd /
	${PHPBIN} -b 127.0.0.1:${PORT} &
}

stop_fcgi_server() {
	killall -15 php-cgi
}

case "$1" in
	start)
		start_fcgi_server
		;;
	stop)
		stop_fcgi_server
		;;
	restart)
		stop_fcgi_server
		start_fcgi_server
		;;
	*)
		echo "Usage: $0 {start|stop|restart}"
		exit 1
		;;
esac

exit 0
