#!/usr/bin/env bash
# system/limits -- open-file limits for nginx and php-fpm
#
# A busy site fails with "too many open files" when the limit is left at the
# distribution default, and the error looks like an application bug.
set -o pipefail
SELF=$(readlink -f "${BASH_SOURCE[0]}")
NV_BASE=$(cd "$(dirname "$SELF")/../../.." && pwd)
export NV_BASE
# shellcheck source=/dev/null
. "$NV_BASE/lib/core/bootstrap.sh"

nv_require_root || exit 1
ui_header "$(t sys_m_limits)"

cfg=/etc/security/limits.d/99-nhanhvps.conf
ui_kv "$(t limits_shell)" "$(ulimit -n 2>/dev/null || echo '?')"
ui_kv "$(t limits_file)"  "$cfg"
[ -f "$cfg" ] && sed -n '1,10p' "$cfg" | sed 's/^/  /'
ui_blank

printf '  %s [65535]: ' "$(t limits_prompt)"
read -r val || exit 130
val=$(nv_trim "$val"); [ -z "$val" ] && val=65535
case $val in ''|*[!0-9]*) ui_err "$(t ui_invalid_number)"; exit 2 ;; esac
[ "$val" -lt 1024 ] && { ui_err "$(t limits_too_small)"; exit 2; }

nv_backup_path "$cfg" limits >/dev/null 2>&1 || true
cat >"$cfg" <<EOF
# managed by nhanhvps
*    soft nofile $val
*    hard nofile $val
root soft nofile $val
root hard nofile $val
www-data soft nofile $val
www-data hard nofile $val
EOF

# systemd services need the limit in their own unit context
if [ -d /etc/systemd/system/nginx.service.d ] || nv_have systemctl; then
    install -d -m 0755 /etc/systemd/system/nginx.service.d
    cat >/etc/systemd/system/nginx.service.d/limits.conf <<EOF
[Service]
LimitNOFILE=$val
EOF
    systemctl daemon-reload 2>/dev/null || true
fi

nv_trace limits "nofile=$val"
ui_ok "$(t limits_done "$val")"
ui_info "$(t limits_note)"
exit 0
