#!/bin/bash
# 00-optional-tuning.sh: file descriptor limits
# Idempotent — safe to re-run without duplicating entries
#
# NOTE: swap is intentionally NOT configured — OOM will fail hard and
# visibly instead of degrading silently under memory pressure (deliberate choice).
# If swap is added later, also set vm.swappiness = 10 (prefer RAM, use swap
# only as a last resort) — otherwise the default swappiness=60 kicks in too eagerly.

if [ "$EUID" -ne 0 ]; then echo "Error: Run as root"; exit 1; fi

echo "==> Setting file descriptor limits (/etc/security/limits.d/99-custom.conf)..."
cat > /etc/security/limits.d/99-custom.conf <<EOF
* soft nofile 65535
* hard nofile 65535
root soft nofile 65535
root hard nofile 65535
www-data soft nofile 65535
www-data hard nofile 65535
EOF

if [ $(wc -l < /proc/swaps) -gt 1 ]; then
    echo "==> Swap detected — setting vm.swappiness=10 (/etc/sysctl.d/99-swappiness.conf)..."
    echo "vm.swappiness = 10" > /etc/sysctl.d/99-swappiness.conf
    sysctl --system
else
    echo "==> No swap configured — skipping vm.swappiness."
fi

echo "==> Tuning applied. A new session/re-login may be required for the limits to take effect."