#! /bin/sh

### BEGIN INIT INFO
# Provides:          php-cgi
# Required-Start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: spawns the php-cgi
# Description:       spawns the php-cgi
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
NAME=php-cgi
DESC=php-cgi

test -x $DAEMON || exit 0

PIDFILE="/var/run/$NAME.pid"
DAEMON="/usr/bin/php-cgi"
SPAWN_FCGI="/usr/bin/spawn-fcgi"
FCGI_PORT=9000
FCGI_USER="www-data"
FCGI_GROUP="www-data"
FCGI_CHILDREN=4

PHP_FCGI_MAX_REQUESTS=1000
export PHP_FCGI_MAX_REQUESTS

# Include php-cgi defaults if available
if [ -f /etc/default/php-cgi ] ; then
        . /etc/default/php-cgi
fi

SPAWN_FCGI_OPTS="-f $DAEMON -a 127.0.0.1 -p $FCGI_PORT -u $FCGI_USER -g $FCGI_GROUP -C $FCGI_CHILDREN -P $PIDFILE"

set -e

. /lib/lsb/init-functions

case "$1" in
  start)
        echo -n "Starting $DESC: "
        start-stop-daemon --start --quiet --pidfile $PIDFILE --exec "$SPAWN_FCGI" -- $SPAWN_FCGI_OPTS || true
        echo "$NAME."
        ;;
  stop)
        echo -n "Stopping $DESC: "
        start-stop-daemon --stop --quiet --pidfile $PIDFILE --exec "$DAEMON" || true
        echo "$NAME."
        ;;
  restart)
        echo -n "Restarting $DESC: "
        start-stop-daemon --stop --quiet --pidfile $PIDFILE --exec "$DAEMON" || true
        sleep 1
        start-stop-daemon --start --quiet --pidfile $PIDFILE --exec "$SPAWN_FCGI" -- $SPAWN_FCGI_OPTS || true
        echo "$NAME."
        ;;
  status)
        status_of_proc -p $PIDFILE "$DAEMON" php-cgi && exit 0 || exit $?
        ;;
  *)
        echo "Usage: $NAME {start|stop|restart|status}" >&2
        exit 1
        ;;
esac

exit 0
