#!/bin/sh

set -e

sasluser="user$$"
saslpass="pass$$"
ldap_admin_pw="ldapadminpw$$"
mydomain="example.fake"
myhostname="server.${mydomain}"
ldap_suffix="dc=example,dc=fake"
ldap_admin_dn="cn=admin,${ldap_suffix}"
mechs_to_test="SCRAM-SHA-256 SCRAM-SHA-1 DIGEST-MD5 CRAM-MD5"

cleanup() {
    rm -f /etc/sasldb2
    # This is not meant to fully restore the state, but just don't leave a file
    # with clear text and easy to guess credentials lying around.
    # From sasl2-bin's postinst
    echo '!' | saslpasswd2 -c 'no:such:user'
    saslpasswd2 -d 'no:such:user'
    chmod 0640 /etc/sasldb2
    chown root:sasl /etc/sasldb2
}


trap cleanup EXIT

setup_slapd() {
    local domain="$1"
    local password="$2"
    # MUST use REAL TABS as delimiters below!
    debconf-set-selections << EOF
slapd	slapd/domain	string	${domain}
slapd	shared/organization	string	${domain}
slapd	slapd/password1	password	${password}
slapd	slapd/password2	password	${password}
EOF
    rm -rf /var/backups/*slapd* /var/backups/unknown*ldapdb
    gpasswd -a openldap sasl > /dev/null 2>&1 || :
    dpkg-reconfigure -fnoninteractive -pcritical slapd 2>&1
    systemctl restart slapd # http://bugs.debian.org/1010678
    echo
    echo "Configuring slapd to use the sasldb auxprop plugin for SASL shared secret mechanisms"
    ldapmodify -Y EXTERNAL -H ldapi:/// 2>&1 <<EOF
dn: cn=config
changetype: modify
replace: olcSaslAuxprops
olcSaslAuxprops: sasldb

EOF
}

echo "Setting up slapd"
setup_slapd "${mydomain}" "${ldap_admin_pw}"

echo "Create test user ${sasluser} in sasldb"
rm -f /etc/sasldb2
echo -n "${saslpass}" | saslpasswd2 -c -p "${sasluser}" -u "${mydomain}"
chown root:sasl /etc/sasldb2
chmod 0640 /etc/sasldb2
echo

echo "Testing shared secret mechanisms one by one"
echo

for mech in ${mechs_to_test}; do
    echo "Testing mechanism ${mech}"
    ldapwhoami -Y ${mech} -U "${sasluser}"@"${mydomain}" -w "${saslpass}" 2>&1
    echo
done
