#!/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/
#

# 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

# 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
}

case "$reason" in
	BOUND|RENEW|REBIND|REBOOT)
	hostname=$(ip2hostname $new_ip_address)
	if [ -z "$hostname" ] ; then
		logger -t dhclient-exit-hooks.d/hostname "unable to find hostname from DHCP IP address $new_ip_address, not updating current hostname"
	elif [ "$hostname" != "$(uname -n)" ] ; then
		echo dhclient-exit-hooks.d/hostname: Dynamic IP address = $new_ip_address
		echo $hostname > /etc/hostname
		hostname $hostname
		echo dhclient-exit-hooks.d/hostname: Dynamic Hostname = $hostname
		logger -t dhclient-exit-hooks.d/hostname "changing hostname to $hostname based on DHCP IP address $new_ip_address"
	fi
	;;
esac
