#!/bin/bash

MAC=`/sbin/ifconfig eth0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}' | tr '[A-Z]' '[a-z]'`
if grep -q $MAC HOSTS; then
  HOSTNAME=`grep $MAC HOSTS | cut -d\| -f1`
  if [ "$HOSTNAME" = "`hostname`" ]; then
    echo 'hostname is already correct'
    exit 1
  fi
  echo "setting hostname to $HOSTNAME"
  echo "$HOSTNAME" > /tmp/HOSTNAME.$$
  sudo rm -f /etc/hostname
  sudo mv /tmp/HOSTNAME.$$ /etc/hostname
  sudo chown root:root /etc/hostname
  sudo chmod 644 /etc/hostname
  sudo /etc/init.d/hostname.sh
  exit 0
else
  echo "cannot determine hostname"
  exit 1
fi
