#!/bin/bash
#  _    _          ___           __ _     (R)
# | |  (_)_ _____ / __|___ _ _  / _(_)__ _
# | |__| \ V / -_) (__/ _ \ ' \|  _| / _` |
# |____|_|\_/\___|\___\___/_||_|_| |_\__, |
#                                    |___/
# Copyright (c) 2009-2025 LiveConfig GmbH.
# ----------------------------------------------------------------------------
# /etc/init.d/nginx-php-fcgi
# Init script for starting PHP FCGI instances with NGINX
# ----------------------------------------------------------------------------

### BEGIN INIT INFO
# Provides:          nginx-php-fcgi
# Required-Start:    $nginx
# Required-Stop:     $nginx
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start PHP FCGI instances for NGINX
# Description:       This scripts starts all required PHP FCGI instances
#                    when using NGINX with LiveConfig
### END INIT INFO

COMMAND=$1
CONFIG=$2
PHP_CGI=/usr/bin/php-cgi
RETVAL=0

# RedHat/CentOS:
if [ -f /etc/rc.d/init.d/functions ]; then
  . /etc/rc.d/init.d/functions
fi

# check permissions
[ "$EUID" != "0" ] && echo 'You need to have root priviliges' && exit 4

# locate path with nginx vhost config files
for i in "$NGINX_CONFIGPATH" /etc/nginx/sites-enabled /etc/nginx/sites-available /etc/nginx/vhosts.d; do
    [ -n "$i" ] && [ -d "$i" ] && CONFIGPATH=$i && break
done
[ -z "$CONFIGPATH" ] && echo 'Config directory not found' && exit 1

if [ -z "$CONFIG" ]; then
    CONFIG="$CONFIGPATH/*.conf"
else
    [ ! -f "$CONFIGPATH/$CONFIG.conf" ] && echo "Configuration file $CONFIGPATH/$CONFIG.conf not found" && exit 1
    CONFIG="$CONFIGPATH/$CONFIG.conf"
fi

start() {
    echo -n "Starting PHP FastCGI for NGINX:"

    # set explicit umask:
    umask 0022

    # if cgroups & systemd are available, prepare own cgroup:
    if [ -d /sys/fs/cgroup/systemd ]; then
        [ ! -d /sys/fs/cgroup/systemd/liveconfig/nginx-php-fcgi ] && mkdir -p /sys/fs/cgroup/systemd/liveconfig/nginx-php-fcgi
        echo $$ >>/sys/fs/cgroup/systemd/liveconfig/nginx-php-fcgi/tasks
    fi

    for i in $CONFIG; do
        NGINX_FCGI_USER=`awk -F '=' '$1 ~ /^# NGINX_FCGI_USER/ { print $2}' $i`
        [ -z "$NGINX_FCGI_USER" ] && continue
        echo -n " $NGINX_FCGI_USER"

        IDX=""
        while grep "^# NGINX_FCGI${IDX}_SOCKET" "$i" 1>/dev/null 2>&1; do
            # get all other options:
            NGINX_FCGI_SOCKET=`awk -F '=' "\\$1 ~ /^# NGINX_FCGI${IDX}_SOCKET/ { print \\$2}" $i`
            NGINX_FCGI_CHILDREN=`awk -F '=' "\\$1 ~ /^# NGINX_FCGI${IDX}_CHILDREN/ { print \\$2}" $i`
            NGINX_FCGI_MAX_REQUESTS=`awk -F '=' "\\$1 ~ /^# NGINX_FCGI${IDX}_MAX_REQUESTS/ { print \\$2}" $i`
            NGINX_FCGI_INI_PATH=`awk -F '=' "\\$1 ~ /^# NGINX_FCGI${IDX}_INI_PATH/ { print \\$2}" $i`
            NGINX_FCGI_BIN=`awk -F '=' "\\$1 ~ /^# NGINX_FCGI${IDX}_BIN/ { print \\$2}" $i` || NGINX_FCGI_BIN=$PHP_CGI
            PIDFILE=`echo -n "$NGINX_FCGI_SOCKET" | sed -e 's/\.sock$/.pid/'`

            # start PHP-FCGI instance for this user
            PHP_CGI_ARGS="- USER=$NGINX_FCGI_USER PATH=/usr/bin PHP_FCGI_CHILDREN=$NGINX_FCGI_CHILDREN PHP_FCGI_MAX_REQUESTS=$NGINX_FCGI_MAX_REQUESTS PHPRC=$NGINX_FCGI_INI_PATH $NGINX_FCGI_BIN -b $NGINX_FCGI_SOCKET"
            if [ -x /sbin/start-stop-daemon ]; then
                start-stop-daemon --quiet --start --background --make-pidfile --pidfile $PIDFILE --chuid "$NGINX_FCGI_USER" --exec /usr/bin/env -- $PHP_CGI_ARGS
            elif [ -f /etc/rc.d/init.d/functions ]; then
                # use "daemon" shell function (RedHat/CentOS)
                daemon --user "$NGINX_FCGI_USER" "/bin/env $PHP_CGI_ARGS &"
            else
                $?=1
            fi
            if [ "$?" != "0" ]; then
                echo -n "[FAILED]"
                RETVAL=1
            fi

            if [ -z "$IDX" ]; then
                IDX=1
            else
                IDX=$(($IDX+1))
            fi
        done
    done
    echo " - done."
}

stop() {
    echo -n "Stopping PHP FastCGI for NGINX:"
    for i in $CONFIG; do
        NGINX_FCGI_USER=`awk -F '=' '$1 ~ /^# NGINX_FCGI_USER/ { print $2}' $i`;
        [[ -z "$NGINX_FCGI_USER" ]] && continue
        NGINX_FCGI_CONF=`awk -F '=' '$1 ~ /^# NGINX_FCGI_CONF/ { print $2}' $i`;

        SEEN=""
        IDX=""
        while grep "^# NGINX_FCGI${IDX}_SOCKET" "$i" 1>/dev/null 2>&1; do
            NGINX_FCGI_SOCKET=`awk -F '=' "\\$1 ~ /^# NGINX_FCGI${IDX}_SOCKET/ { print \\$2}" $i`
            PIDFILE=`echo -n "$NGINX_FCGI_SOCKET" | sed -e 's/\.sock$/.pid/'`
            if [ "$SEEN" = "" ]; then SEEN="1"; echo -n " $NGINX_FCGI_USER"; fi

            if [ -x /sbin/start-stop-daemon ]; then
                /sbin/start-stop-daemon --quiet --stop --retry=TERM/30/KILL/5 -u "$NGINX_FCGI_USER" --pidfile $PIDFILE > /dev/null
                [ "$?" = "0" ] && rm -f $PIDFILE
            else
                killall -u "$NGINX_FCGI_USER" -TERM php-cgi 2>/dev/null
            fi

            if [ -z "$IDX" ]; then
                IDX=1
            else
                IDX=$(($IDX+1))
            fi
        done

        for PIDFILE in $NGINX_FCGI_CONF/nginx-php-fcgi*.pid; do
            if [ "$SEEN" = "" ]; then SEEN="1"; echo -n " $NGINX_FCGI_USER"; fi
            if [ -x /sbin/start-stop-daemon ]; then
                /sbin/start-stop-daemon --quiet --stop --retry=TERM/30/KILL/5 -u "$NGINX_FCGI_USER" --pidfile $PIDFILE > /dev/null
                [ "$?" = "0" ] && rm -f $PIDFILE
            else
                killall -u "$NGINX_FCGI_USER" -TERM php-cgi 2>/dev/null
            fi
        done
    done
    echo " - done."
}
 
case "$COMMAND" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
    sleep 1
        start
        ;;
    *)
        echo "Usage: nginx-php-fcgi {start|stop|restart} [config]"
        RETVAL=1
        ;;
esac
exit $RETVAL

# <EOF>-----------------------------------------------------------------------
