#!/bin/bash
#
# script: rc.php-fpm
#
# Provides:          php-fpm
# Required-Start:    $remote_fs $network
# Required-Stop:     $remote_fs $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts php-fpm
# Description:       starts the PHP FastCGI Process Manager daemon
#
# LimeTech - modified for Unraid OS
# Bergware - modified for Unraid OS, October 2023

DAEMON="PHP-fpm daemon"
PHP_FPM_BIN="/usr/sbin/php-fpm"
PHP_FPM_CONF="/etc/php-fpm.conf"
PHP_FPM_PID="/var/run/php-fpm.pid"

# run & log functions
. /etc/rc.d/rc.runlog

# LimeTech - need  --allow-to-run-as-root
PHP_OPTS="--fpm-config $PHP_FPM_CONF --pid $PHP_FPM_PID  --allow-to-run-as-root"

php_fpm_waitfor(){
  local TIMER=35
  while [[ $TIMER -gt 0 ]]; do
    case "$1" in
      'created') [[ -f $2 ]] && return 0 ;;
      'removed') [[ -f $2 ]] || return 0 ;;
    esac
    ((TIMER--))
    sleep 1
  done
  return 1
}

php_fpm_start(){
  log "Starting $DAEMON..."
  local REPLY
  run $PHP_FPM_BIN --daemonize $PHP_OPTS
  if [[ $? -eq 0 ]]; then
    if php_fpm_waitfor created $PHP_FPM_PID; then REPLY="Started"; else REPLY="Failed"; fi
  else
    REPLY="Already started"
  fi
  log "$DAEMON...  $REPLY."
}

php_fpm_stop(){
  log "Stopping $DAEMON..."
  local REPLY
  if [[ -r $PHP_FPM_PID ]]; then
    run kill -QUIT $(cat $PHP_FPM_PID)
    if php_fpm_waitfor removed $PHP_FPM_PID; then REPLY="Stopped"; else REPLY="Failed"; fi
  else
    REPLY="Already stopped"
  fi
  log "$DAEMON...  $REPLY."
}

php_fpm_restart(){
  log "Restarting $DAEMON..."
  php_fpm_stop
  sleep 1
  php_fpm_start
}

php_fpm_reload(){
  log "Reloading $DAEMON..."
  if [[ ! -r $PHP_FPM_PID ]]; then
    log "$DAEMON...  Warning, no pid file found."
    exit 1
  fi
  kill -USR2 $(cat $PHP_FPM_PID)
  log "$DAEMON...  Reloaded."
}

php_fpm_force_quit(){
  log "Terminating $DAEMON..."
  if [[ ! -r $PHP_FPM_PID ]]; then
    log "$DAEMON...  Warning, no pid file found."
    exit 1
  fi
  kill -TERM $(cat $PHP_FPM_PID)
  php_fpm_waitfor removed $PHP_FPM_PID
  log "$DAEMON...  $REPLY."
}

php_fpm_status(){
  if [[ ! -r $PHP_FPM_PID ]]; then
    echo "$DAEMON is not running."
    exit 1
  fi
  PID=$(cat $PHP_FPM_PID)
  if ps -p $PID | grep -q $PID; then
    echo "$DAEMON is currently running."
  else
    echo "$DAEMON is dead but PID file exists"
    exit 1
  fi
}

case "$1" in
'start')
  php_fpm_start
  ;;
'stop')
  php_fpm_stop
  ;;
'restart')
  php_fpm_restart
  ;;
'reload')
  php_fpm_reload
  ;;
'force-quit')
  php_fpm_force_quit
  ;;
'configtest')
  $PHP_FPM_BIN -t
  ;;
'status')
  php_fpm_status
  ;;
*)
  echo "Usage: $BASENAME start|stop|restart|reload|force-quit|configtest|status"
  exit 1
esac
exit 0
