#!/bin/bash

# Get a list of ip addresses in use by vswif devices.
getIPs() {
   /sbin/ifconfig | perl -e '$_=join("",<>); map {print "$_\n"} m/^vswif\d+.*\s+inet addr:([0-9\.]+)/mg' 
}

# Try to get a valid COS IP address. Due to
# certain (mis)configurations `hostname -i' sometimes returns 
# the loopback ip. Try harder by looking at all vswifN devices, and
# if there is only one configured device us its ip (if there
# are more, bail and let support deal).
getCOSIP() {
   IpAddr=`hostname -i | grep -E '^([0-9]{1,3}\.){3}[0-9]{1,3}\W*$'`
   if [ "$IpAddr" == "127.0.0.1" ] ||  [ "$IpAddr" == "" ]; then
      if [ "`getIPs| wc -l`" -eq 1 ];  then
         IpAddr="`getIPs`"
      else
         # give up (more than one, or no ip addresses)
         IpAddr=""
      fi
   fi

   echo "$IpAddr"
}

oldHostName=`esxcfg-advcfg -q -g  /Misc/HostName`
newHostName=`hostname`
if [ "$oldHostName" != "$newHostName" ]; then
   #echo "Changing hn from '$oldHostName' to '$newHostName'"
   esxcfg-advcfg -q -s "$newHostName" /Misc/HostName
fi

oldIP=`esxcfg-advcfg -q -g  /Misc/HostIPAddr`
newIP=`getCOSIP`
if [ "$oldIP" != "$newIP" ]; then
   #echo "Changing ip from '$oldIP' to '$newIP'"
   esxcfg-advcfg -q -s "$newIP" /Misc/HostIPAddr
fi
