#!/usr/bin/bash

if [ -f /etc/systemd/system/httpd.service.d/autotune.conf ]; then
    exit 0
fi

#
# TODO: ulimits!
#

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
)

MAX_CLIENTS_CPU=$[192*NPROC]
MAX_CLIENTS_RAM=$[MEMMB/32]
MAX_CLIENTS=$(min $MAX_CLIENTS_CPU $MAX_CLIENTS_RAM)

# Needs to be an integer multiple of ThreadsPerChild
MAX_CLIENTS=$(max 64 $[MAX_CLIENTS/64*64])

MAX_SERVERS=$((MAX_CLIENTS/64))


cat <<-EOD | augtool --autosave
set /files/etc/httpd/conf.d/ng-05-tuning.conf/directive[.='ServerLimit'] ServerLimit
set /files/etc/httpd/conf.d/ng-05-tuning.conf/directive[.='ServerLimit']/arg $MAX_SERVERS
set /files/etc/httpd/conf.d/ng-05-tuning.conf/directive[.='MaxRequestWorkers'] MaxRequestWorkers
set /files/etc/httpd/conf.d/ng-05-tuning.conf/directive[.='MaxRequestWorkers']/arg $MAX_CLIENTS
EOD

# TODO: Why won't augtool do this?
mkdir -p /etc/systemd/system/httpd.service.d
cat <<-EOD >/etc/systemd/system/httpd.service.d/autotune.conf
#
# * DO NOT EDIT * DO NOT EDIT * DO NOT EDIT *
#
#  This file is managed by autotune-httpd
#
#  * DO NOT EDIT * DO NOT EDIT * DO NOT EDIT *
#
[Service]
LimitNOFILE = $[MAX_CLIENTS*4]

EOD

systemctl daemon-reload
