#!/bin/sh -e
#
# Author: Petter Reinholdtsen <pere@td.org.uit.no>
# Date:   2002-08-06
#
# Set current hostname to match the IP address on eth0.  This is
# useful when getting the IP address from DHCP.

PATH="/sbin:$PATH"

INTERFACE=eth0

if [ "-q" = "$1" ] ; then
    QUIET=true
    shift
else
    QUIET=false
fi

LC_ALL=C
export LC_ALL

# Extract current IP
IP=`ifconfig $INTERFACE 2>&1 |grep 'inet addr:'|tr a-zA-Z: " "|awk '{print $1}'`

if [ "$IP" ] ; then

   case  `dpkg -S /usr/bin/host |cut -d":" -f1` in
      #bind9-host
      bind9-host)
          DNSNAME=`host $IP | grep pointer | awk '{ print $5 }'  | sed -e 's/\.$//g' `
          ;;
      #default to old way
      host | *)
          DNSNAME=`host $IP | grep Name: | awk '{ print $2 }'`
          ;;
   esac

    if [ "$DNSNAME" ] ; then
	if hostname $DNSNAME 2>/dev/null ; then
	    [ true != "$QUIET" ] && echo "info: Setting hostname to DNS name $DNSNAME [$IP]."
	    echo $DNSNAME > /etc/hostname
	else
	    [ true != "$QUIET" ] && echo "error: Unable to set hostname to $DNSNAME."
	    exit 1
	fi
    else
	[ true != "$QUIET" ] && echo "error: Unable to look up $IP using DNS."
	exit 1
    fi
else
    [ true != "$QUIET" ] && echo "error: Unable to determine current IP address."
    exit 1
fi

exit 0
