#!/bin/sh

set -e

#set -x

log() {
    echo "ldap-kerberos-preseed: $@" 1>&2
}
error() {
    log "error: $@"
}

# Preseed LDAP and Kerberos settings on clients based on dynamically
# detected values.
add_preseed() {
    pkg="$1"
    template="$2"
    type="$3"
    value="$4"
    log "Preseeding $template to $value"
    echo $pkg $template $type "$value" | debconf-set-selections || \
	error "Failed to load preseed '$template'"

}

ldapserver="$(debian-edu-ldapserver -f || true)"
if [ "$ldapserver" ] ; then
    add_preseed nslcd nslcd/ldap-uris string "ldap://$ldapserver"

    # Tell lwat to use FQDN for LDAP server, to get SSL cert check working
    add_preseed lwat shared/ldapns/ldap-server string $ldapserver
    
    ldapbase="$(debian-edu-ldapserver -f -s $ldapserver -b || true)"
    if [ "$ldapbase" ] ; then
	add_preseed nslcd nslcd/ldap-base string "$ldapbase"
	add_preseed nslcd nslcd/ldap-reqcert select demand
    else
	error "Unable to find LDAP base"
    fi
else
    error "Unable to find LDAP server"
fi

krbrealm="$(debian-edu-ldapserver -f -r || true)"
if [ "$krbrealm" ] ; then
    krbserver="$(debian-edu-ldapserver -f -k || true)"
    add_preseed krb5-config krb5-config/default_realm string "$krbrealm"
    if [ "$krbserver" ] ; then
	add_preseed krb5-config krb5-config/kerberos_servers string "$krbserver"
	add_preseed krb5-config krb5-config/admin_server string "$krbserver"
    else
	error "Unable to find Kerberos server"
    fi
else
    error "Unable to find Kerberos realm"
fi
