#!/sbin/runscript

set_phpvars() {
  CFGNAME=${SVCNAME#php-fpm-}
	PHPSLOT="$(eselect php show fpm)"
	PHP_FPM_PID="/var/run/php-fpm-${CFGNAME}.pid"
  PHP_FPM_LISTEN_ADDRESS="/var/run/php-fpm-${CFGNAME}.socket"
  if [ ! -f /etc/conf.d/$SVCNAME ] ; then
    eerror "Config file /etc/conf.d/$SVCNAME not found!"
    eend 1
    exit 1
  fi
  source /etc/conf.d/${SVCNAME}
  if [[ -z "$PHP_FPM_CONF" ]] ; then
    PHP_FPM_MAIN_CONF="/etc/php/fpm-${PHPSLOT}/php-fpm.conf"
    PHP_FPM_CONF="/etc/php/fpm-${PHPSLOT}/php-fpm-${CFGNAME}.conf"
    PHP_FPM_LOGFILE="/var/log/apache2/php-fpm-${CFGNAME}.log"
    sed "s/^user *=.*$/user = $PHP_FPM_USER/;s/^group *=.*$/group = $PHP_FPM_GROUP/" "${PHP_FPM_MAIN_CONF}" | \
      sed "s#^listen *=.*\$#listen = $PHP_FPM_LISTEN_ADDRESS#" |
      sed "s#^error_log *=.*\$#error_log = ${PHP_FPM_LOGFILE}#" > "$PHP_FPM_CONF"
    if [[ -n "$PHP_FPM_CHROOT" ]] ; then
      echo "chroot = $PHP_FPM_CHROOT" >> "$PHP_FPM_CONF"
    fi
  fi
}

extra_commands="depend"
extra_started_commands="reload"

depend() {
	need net
	use apache2 lighttpd nginx
}

start() {
        set_phpvars
        ebegin "Starting PHP FastCGI Process Manager ($CFGNAME)"

        start-stop-daemon --start --pidfile ${PHP_FPM_PID} --exec \
            /usr/lib/${PHPSLOT}/bin/php-fpm -- -y "${PHP_FPM_CONF}" -g "${PHP_FPM_PID}" \
            -d www.user=${PHP_FPM_USER} -d www.group=${PHP_FPM_GROUP} -d www.listen_address=${PHP_FPM_LISTEN_ADDRESS}
        local i=0
        local timeout=5
        while [ ! -f ${PHP_FPM_PID} ] && [ $i -le $timeout ]; do
            sleep 1
            i=$(($i + 1))
        done

        [ $timeout -gt $i ]
        eend $?
}

stop() {
        set_phpvars
        ebegin "Stopping PHP FastCGI Process Manager ($CFGNAME)"
        start-stop-daemon --signal QUIT --stop --exec /usr/lib/${PHPSLOT}/bin/php-fpm --pidfile ${PHP_FPM_PID}
        eend $?
}

reload() {
    set_phpvars
    ebegin "Reloading PHP FastCGI Process Manager ($CFGNAME)"
    [ -f ${PHP_FPM_PID} ] && kill -USR2 $(cat ${PHP_FPM_PID})
    eend $?
}
