#!/bin/sh
#
# Purpose: Used by dhclient-script to set the hostname of the system
# to match the DNS information for the host as provided by DHCP.
#
# This script is based on code found on the web:
# http://www.debian-administration.org/articles/447 and
# http://nxhelp.com/blog/2013/01/24/automatically-set-hostname-from-dhcp/
#

PATH=/sbin:$PATH
export PATH

# Should not update hostname on Main-Server, Roaming-Workstation and Standalone
if [ -r /etc/debian-edu/config ] ; then
	. /etc/debian-edu/config
	case "$PROFILE" in
	Workstation|Thin-Client-Server|Minimal)
		;;
	*)
		exit 0
		;;
	esac
else
	exit 0
fi

log() {
    logger -t dhclient-exit-hooks.d/hostname "$1"
}

# Map IP to FQDN
ip2hostname() {
    ip=$1
    host $new_ip_address | grep 'domain name pointer' | cut -d ' ' -f 5 | \
	rev |cut -d '.' -f 2-|rev
}

# Generate FQDN based on hardware MAC address
ether2hostname() {
    # Pick the first MAC address listed by ifconfig, and use it to
    # generate a unique host name for the machine.
    mac=$(ifconfig | awk '/Link encap:Ethernet  HWaddr/ { print $5; exit}'| \
	  sed 's/[^0-9a-f-]/-/gi')
    if [ "$mac" ] ; then
	fqdn="auto-mac-$mac.intern";
	echo $fqdn
    fi
}

sethostname() {
    hostname="$1"
    namesource="$2"
    echo $hostname > /etc/hostname
    hostname $hostname
    log "changing hostname to $hostname based on $namesource"
}

case "$reason" in
	BOUND|RENEW|REBIND|REBOOT)
	namesource="DHCP IP address $new_ip_address"
	hostname=$(ip2hostname $new_ip_address)
	if [ -z "$hostname" ] ; then
		namesource="hardware MAC address"
		hostname=$(ether2hostname)
	fi
	if [ -z "$hostname" ] ; then
		log "unable to find hostname from DHCP IP address $new_ip_address and MAC address, not updating current hostname"
	elif [ "$hostname" != "$(uname -n)" ] ; then
		echo dhclient-exit-hooks.d/hostname: Dynamic IP address = $new_ip_address
		sethostname "$hostname" "$namesource"
		echo dhclient-exit-hooks.d/hostname: Dynamic Hostname = $hostname
	fi
	;;
esac
