# syntax=docker/dockerfile:1.7
ARG MARIADB_VERSION=latest

FROM mariadb:${MARIADB_VERSION}

# ── AD/LDAP authentication via PAM ──────────────────────────────────────────
# MariaDB Community has no native LDAP auth plugin, so AD logins go through the
# auth_pam plugin -> a PAM "mariadb" service -> daemonless pam_ldap doing an
# LDAP search+bind against Active Directory. This is the analogue of the pgpool
# `ldap` method in pool_hba.conf; deliberately NO SSSD/nslcd daemon is added.
#
# libpam-ldap is the daemonless PAM/LDAP module. The auth_pam plugin ships with
# recent MariaDB; the separate plugin package (older layouts) is installed
# best-effort and also fixes the setuid auth_pam_tool helper permissions.
# Either source must leave auth_pam.so in place: 10-plugins.cnf loads it
# unconditionally, so a missing .so would only surface as a server that refuses
# to start.
RUN set -eu; \
    apt-get update; \
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
      libpam-ldap \
      ca-certificates \
      gettext-base; \
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
      mariadb-plugin-auth-pam || true; \
    rm -rf /var/lib/apt/lists/*; \
    plugin=/usr/lib/mysql/plugin/auth_pam.so; \
    [ -e "$plugin" ] || { echo "auth_pam: missing $plugin" >&2; exit 1; }

# ── Layered configuration ───────────────────────────────────────────────────
# Mirror the postgres image: image-owned defaults load first, user overrides
# last (last-wins). The stock image already reads /etc/mysql/conf.d and
# /etc/mysql/mariadb.conf.d; we append two include dirs AFTER those so:
#   image.conf.d -> our defaults (override the base image's 50-server.cnf)
#   site.conf.d  -> a clean "mount your *.cnf here" area (wins over everything)
RUN set -eu; \
    mkdir -p /etc/mysql/image.conf.d /etc/mysql/site.conf.d; \
    { \
      echo '!includedir /etc/mysql/image.conf.d/'; \
      echo '!includedir /etc/mysql/site.conf.d/'; \
    } >> /etc/mysql/mariadb.cnf
COPY conf.d/ /etc/mysql/image.conf.d/

# PAM service definition for MariaDB logins (auth_pam calls service "mariadb").
COPY pam.d/mariadb /etc/pam.d/mariadb

# Entrypoint wrapper: renders /etc/pam_ldap.conf from env (keeps the AD bind
# secret out of the image), then hands off to the stock mariadb entrypoint.
COPY --chmod=0755 docker-entrypoint.sh /usr/local/bin/ldap-entrypoint.sh

# Report health via the image's bundled healthcheck helper.
HEALTHCHECK --interval=10s --timeout=5s --retries=5 --start-period=15s \
  CMD healthcheck.sh --connect --innodb_initialized || exit 1

ENTRYPOINT ["ldap-entrypoint.sh"]
CMD ["mariadbd"]
