#!/bin/bash
set -euxo pipefail

export DEBIAN_FRONTEND=noninteractive

debconf-set-selections << eof
slapd slapd/password1 password secret
slapd slapd/password2 password secret
slapd slapd/domain string example.com
slapd slapd/organization string example.com
eof

apt-get -y install slapd

# test if slapd is running and apparmor is active
test "$(aa-enabled)" = "Yes"
if slapd_aa_status="$(aa-status --json | jq -r .profiles.\"/usr/sbin/slapd\")"; then
    # slapd profile must be enforce
    test "$slapd_aa_status" = "enforce"
    # current slapd in enforce mode
    slapd_pid="$(systemctl show --property MainPID --value slapd.service)"
    test "$(cat /proc/${slapd_pid}/attr/current)" = "/usr/sbin/slapd (enforce)"
elif [ "$(dpkg-vendor --query Vendor)-$(dpkg --print-architecture)" = "Ubuntu-armhf" ]; then
    echo "WARNING: failed to check for apparmor profile."
    echo "On armhf and Ubuntu DEP8 infrastructure, this is not a fatal error."
    echo "See LP: #2008393 for details."
else
    echo "slapd not running in apparmor enforce mode."
    exit 1
fi


test "$(ldapwhoami -x -D 'cn=admin,dc=example,dc=com' -w secret)" = 'dn:cn=admin,dc=example,dc=com'
