#!/bin/sh

set -e

LC_ALL=C
export LC_ALL

find_dns_domain() {
    if [ "$1" ] ; then
	domain=$1
    else
	domain="$(hostname -d 2>/dev/null || true)"
	# If hostname is not FQDN, look in DNS setup instead, to
	# increase the chance of the automatic setup to work.
	if [ -z "$domain" ] || [ "(null)" = "$domain" ] || [ "localdomain" = "$domain" ]; then
	    domain=$(grep search /etc/resolv.conf |awk '{print $2}')
	fi
    fi
    echo $domain
}

domain=$(find_dns_domain "$1")

if ping -c2 syslog.$domain > /dev/null 2>&1; then
    echo syslog.$domain
elif ping -c2 loghost.$domain > /dev/null 2>&1; then
    echo loghost.$domain
elif host=$(host -t SRV _syslog._udp.$domain) ; then
    host=$(echo $host | grep -v NXDOMAIN | awk '{print $NF}' | head -1)	
    if [ "$host" ] ; then 
	echo $host | sed 's/\.$//'
    else
	echo syslog
    fi
else
    echo syslog
fi
