#!/bin/bash
# Use this as a run script with daemontools or runit

## ABSOLUTE path to the spawn-fcgi binary
SPAWNFCGI="/usr/bin/spawn-fcgi"

## ABSOLUTE path to the FastCGI application (php-cgi, dispatch.fcgi, ...)
FCGIPROGRAM="/usr/bin/php5-cgi"

## bind to unix socket
FCGISOCKET="/var/run/lighttpd/your-fcgi-app.sock"

# allowed environment variables separated by spaces
ALLOWED_ENV="PATH USER"

## if this script is run as root switch to the following user
USERID=xxx
SOCKUSERID=www-data
#CHROOT=/home/www/

#RAILS_ENV="production"
#export RAILS_ENV


################## no config below this line

exec 2>&1

if test x$PHP_FCGI_CHILDREN = x; then
  PHP_FCGI_CHILDREN=4
fi

ALLOWED_ENV="$ALLOWED_ENV RAILS_ENV"

if test x$UID = x0; then
  EX="$SPAWNFCGI -n -s $FCGISOCKET -u $USERID -U $SOCKUSERID -C $PHP_FCGI_CHILDREN -- $FCGIPROGRAM"
else
  EX="$SPAWNFCGI -n -s $FCGISOCKET -C $PHP_FCGI_CHILDREN -- $FCGIPROGRAM"
fi

# copy the allowed environment variables
E=

for i in $ALLOWED_ENV; do
  E="$E $i=${!i}"
done

# clean environment and set up a new one
exec env - $E $EX
