#!/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'"
}

sitesummaryserver=sitesummary
if ping -c2 sitesummary > /dev/null 2>&1 ; then
   sitesummaryserver=$(getent hosts sitesummary | awk '{print $2}')
else
    host=$(LC_ALL=C host -N 2 -t SRV _sitesummary._tcp | egrep -v '^;|NXDOMAIN|SERVFAIL' | awk '{print $NF}' | head -1)
    if [ "$host" ] && ping -c2 "$host" ; then
	sitesummaryserver=$(echo $host | sed 's/\.$//')
    fi
fi

# Send sitesummary reports to the central collector
add_preseed sitesummary-client sitesummary-client/collector_url string \
    http://$sitesummaryserver/cgi-bin/sitesummary-collector.cgi
