#!/usr/bin/bash
#
# Author: Song Zhao <szhao@noggin.com.au>
# Date  : Fri, 7 Nov 2014
# 
# passing anything as a cmd line argument will stop all php-fpm services
# without checking if they have any child processes
#

#set -x

php_fpm_services=$(systemctl list-units --type=service --state=running|grep "php-fpm-pool\@"|grep service|awk '{print $1}')
num_php_fpm_services=$(echo $php_fpm_services | wc -w)

if [ $num_php_fpm_services -gt 0 ]; then
  for service in $php_fpm_services
  do
    main_pid=$(systemctl show -p MainPID $service | cut -f2 -d=)
    num_children=$(ps h --ppid "$main_pid" -o pid | wc -w)
    if [ -z $1 ]; then
      if [ $num_children -eq 0 ]; then
        systemctl stop "$service"
      fi
    else
      systemctl stop "$service"
    fi
  done
fi

exit 0

