#!/usr/bin/env bash set -euo pipefail : "${LDAP_SUFFIX:?LDAP_SUFFIX must be set (e.g. dc=infinito,dc=example)}" : "${LDAP_ROOT_DN:?LDAP_ROOT_DN must be set (e.g. cn=administrator,dc=infinito,dc=example)}" : "${LDAP_ROOT_PW:?LDAP_ROOT_PW must be set}" : "${LDAP_LOG_LEVEL:?LDAP_LOG_LEVEL must be set (e.g. stats, stats2, acl, 0)}" SLAPD_D_DIR="/etc/ldap/slapd.d" DB_DIR="/var/lib/ldap" TMP_CONF="/tmp/slapd.conf" log() { echo "[openldap] $*"; } fatal() { echo "[openldap][FATAL] $*" >&2; exit 1; } bootstrap_needed() { [ ! -d "${SLAPD_D_DIR}" ] || [ -z "$(ls -A "${SLAPD_D_DIR}" 2>/dev/null)" ] } has_cn_config() { [ -d "${SLAPD_D_DIR}/cn=config" ] } has_mdb_files() { [ -f "${DB_DIR}/data.mdb" ] || [ -f "${DB_DIR}/data.mdb.lock" ] } detect_module_path() { if [ -d /usr/lib/ldap ]; then echo "/usr/lib/ldap" return 0 fi local p p="$(find /usr/lib -maxdepth 2 -type d -name ldap 2>/dev/null | head -n 1 || true)" if [ -n "${p}" ] && [ -d "${p}" ]; then echo "${p}" return 0 fi echo "/usr/lib/ldap" } detect_schema_dir() { if [ -d /etc/ldap/schema ]; then echo "/etc/ldap/schema" return 0 fi echo "/etc/ldap/schema" } write_slapd_conf() { local hash module_path schema_dir hash="$(slappasswd -s "${LDAP_ROOT_PW}")" module_path="$(detect_module_path)" schema_dir="$(detect_schema_dir)" cat > "${TMP_CONF}" </dev/null || true # nocheck: shell-or-true -- see c4bbbba93: slap_startup opens the not-yet-seeded DB and exits 1 after writing a complete slapd.d; has_cn_config below catches every conversion that really failed chown -R openldap:openldap "${SLAPD_D_DIR}" if ! has_cn_config; then log "slaptest did not generate cn=config; listing:" ls -la "${SLAPD_D_DIR}" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error fatal "cn=config missing after slaptest" fi log "cn=config created successfully" } init_mdb_files_if_needed() { if has_mdb_files; then log "data.mdb already exists; skipping MDB init" return 0 fi log "initializing MDB files via slapadd -n 1 (creates data.mdb)" mkdir -p "${DB_DIR}" chown -R openldap:openldap "${DB_DIR}" local dc dc="$(echo "${LDAP_SUFFIX}" | awk -F'[=,]' '{print $2}' | head -n1)" dc="${dc:-infinito}" cat < rebuilding" bootstrap_cn_config_via_slaptest fi fi init_mdb_files_if_needed chown -R openldap:openldap /run/slapd "${DB_DIR}" "${SLAPD_D_DIR}" chmod 700 "${DB_DIR}" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error log "starting slapd (foreground; drop privileges to openldap)" exec /usr/sbin/slapd \ -F "${SLAPD_D_DIR}" \ -d "${LDAP_LOG_LEVEL}" \ -h "ldap:/// ldapi:///" \ -u openldap -g openldap