#! /bin/sh

#echo "Set to LocalHostName"
PREF=/Library/Preferences/SystemConfiguration/preferences.plist
HOSTS=/etc/hosts
IP=`ifconfig en0 |grep inet |grep netmask |awk -F" " '{print $2}'`
#IP=`cat /etc/lastip`
ETHER=`ifconfig en0 |grep ether |awk -F" " '{print $2}'`

MY_IP=`grep -i ${ETHER} /etc/ethers |awk -F" " '{print $2}'`

if [ -f /etc/LAST_IP ]
then
LAST_IP=`cat /etc/LAST_IP`
els
LAST_IP=""
fi


#if [ "${MY_IP}" = "" -o "${IP}" = "" ]
if [ "${MY_IP}" = "" -o "${MY_IP}" = "${LAST_IP}" ]
then
	exit 0
fi
HOSTNAME=`grep ${MY_IP} ${HOSTS} |awk -F" " '{print $2}'`

# DEBUG
#echo "HOSTNAME MY_IP ETHER IP" > /var/tmp/tnk.txt
#echo "${HOSTNAME} ${MY_IP} ${ETHER} ${IP}" >> /var/tmp/tnk.txt

if [ "${MY_IP}" != "${IP}" ]
then

/usr/sbin/scutil --set ComputerName ${HOSTNAME}
/usr/sbin/scutil --set LocalHostName ${HOSTNAME}

/bin/ed ${PREF} <<EOF >/dev/null
1
/<key>Addresses<\/key>/
++c
<string>${MY_IP}</string>
.
w
q
EOF

#touch /System/Library/CoreServices/ServerVersion.plist
#/usr/sbin/systemsetup -setcomputername $HOSTNAME
#rm /System/Library/CoreServices/ServerVersion.plist
echo ${MY_IP} > /etc/LAST_IP

/sbin/reboot

fi
