# linuxmuster-client-auth
#
# gets ldap configuration from dns
. /etc/linuxmuster-client/auth/config

if [ "${AUTOCONFIGURE_LDAP}" != "YES" ]; then
    echo "Info: Autoconfiguring of LDAP disabled"
    return 0
fi

TEMPLATESDIR="/var/lib/linuxmuster-client-auth/templates"

# determine client ip
clientip=`ifconfig  | grep 255.240.0.0 | awk '{print $2}' | awk -F: '{print $2}'`
clientname=`host $clientip | awk '{print $5}' | cut -d. -f1`
# determine servername
fqsn=`host -v $clientip | grep -A1 AUTHORITY | grep in.addr | awk '{print $5}'`
# determine serverip
serverip=`host $fqsn | awk '{print $4}'`
PARTS=$(echo $fqsn | tr "." "\n")

sn=""
basedn=""
for part in $PARTS; do
    if [ -z ${sn}  ]; then
     sn="$part"
    else
     if [ -z ${basedn} ]; then
    basedn="dc=$part"
     else
    basedn="$basedn,dc=$part"
     fi
    fi
done

echo "Autoconfiguring LDAP auth..."
echo "  Client IP is: <$clientip>"
echo "  Client hostname is: <$clientname>"
echo "  Server IP is: <$serverip>"
echo "  Server name is: <$fqsn>"
echo "  Server host name is: <$sn>"
echo "  BaseDN is: <$basedn>"

# configuring hostname
    if [ ! -z $clientname ]; then
    echo $clientname > /etc/hostname
    fi

if [ "x${basedn}" != "x" ] && [ "x${serverip}" != "x" ]; then
    echo -n "Configuring LDAP client to server ${serverip}, base ${basedn}..."
    # patch template file to /etc
    cd ${TEMPLATESDIR}
    find -type f -name ldap.conf | xargs -i -t sh -c \
        "sed -e 's%@@basedn@@%${basedn}%g
        s%@@serverip@@%${serverip}%g' {} > /{}" 2> /dev/null 1> /dev/null

    echo "  done."
else
    if [ -f /etc/linuxmuster-client/auth/ldap.conf.fallback ]; then
    echo "WARNING: Autoconfiguring LDAP FAILED! Copying /etc/linuxmuster-client/auth/ldap.conf.fallback to /etc/ldap.conf"
    cp /etc/linuxmuster-client/auth/ldap.conf.fallback  /etc/ldap.conf
    fi
fi
