#!/usr/bin/bash

#
# NOTE: The following limits are per-uid pool NOT global!
# TOOD: php memory usage should be parsed from php.ini
#

function min { echo $(($1<$2?$1:$2)); };
function max { echo $(($1>$2?$1:$2)); };

NPROC=$(nproc)
MEMMB=$(
cat /proc/meminfo <(ulimit -m) <(ulimit -v) \
 | awk '/^[0-9]+$/{print int($1/1024)}; /^MemTotal:/{print int($2/1024)}' \
 | sort -n \
 | head -1
)


# No more than 4 workers per core 
PM_MAX_CHILDREN_CPU=$(max 8 $[4*NPROC])

# Allow 75% of the RAM for PHP, then assume
# a 192Mb footprint per worker, this is intended
# to include some padding for related processes
PM_MAX_CHILDREN_RAM=$(max 8 $[MEMMB/4*3/192])

# Now we take the lowest of the CPU or RAM limits as the hard cap
PM_MAX_CHILDREN=$(min $PM_MAX_CHILDREN_CPU $PM_MAX_CHILDREN_RAM)

cat <<-EOD | augtool --noload --noautoload --autosave
set /augeas/load/IniFile/lens PHP.lns
set /augeas/load/IniFile/incl  /etc/php-fpm-pool.d/pool.autotune
load
set /files/etc/php-fpm-pool.d/pool.autotune/.anon/pm.max_children $PM_MAX_CHILDREN
EOD
