#/bin/sh
# resetMAC.sh
#
# resets MAC address depending on HOSTNAME content
#
# created: 26-02-2009
# author: p.zumbruch, GSI
# modified: 27-05-2009

#debug - uncomment to debug
#set -xv

scriptname=resetMAC.sh
sourced='FALSE'
mac=''
interface=eth0

#usage function
usage()
{
  echo
  echo "$scriptname"
  echo "usage: $scriptname [options]" 
  echo 
  echo "Changes the MAC address to end with"
  echo "  the same last 2 digits as the variable HOSTNAME [${HOSTNAME}]" 
  echo "  if HOSTNAME isn't set the result of hostname [$(hostname)] is assigned"
  echo "options:"
  echo "   -h           : this help"  
  echo "   -m baseMAC   : doesn't look for MAC pattern with ifconfig but"
  echo "                   takes MAC as base to be extended by the 2 digits"
  echo "                   baseMAC:XX, where baseMAC is of format aa:bb:cc:dd:ee"  
  echo "   -e interface : uses interface [default:$interface]"
  echo "   -d           : debug mode sets set -xv"
  echo
}

#eval options
while getopts de:hm: arg
do
  case $arg in
    \? | h ) usage ; 
             exit 0;
             shift ;; 
    m ) mac=$OPTARG:XX;
        shift 2;;
    e ) interface=$OPTARG;
        shift 2;;
    d ) set -xv 
        shift;;
  esac
done

#replace and execute
HOSTNAME=${HOSTNAME:=$(hostname)}
if [ ! -z ${HOSTNAME%??} ]
then
  number=${HOSTNAME##${HOSTNAME%??}}

  if [ -z ${mac} ]
  then
    found='FALSE'
    for item in $(ifconfig $interface | grep HWaddr)
    do 
      echo $item | grep -q '..:..:..:..:..:..' 
      if [ $? -eq 0 ]
      then 
          mac=$item  
          found='TRUE' 
          break
      fi
    done
    if [ $found = 'FALSE' ]
    then
       echo "$scriptname: Error: couldn't find any match for $interface" >/dev/stderr
       exit 1;
    fi
  fi
  
  [ ${#mac} -ne 17 ] || echo ${mac} | grep -v -q '..:..:..:..:..:..'
  if [ $? -eq 0 ] 
  then
    echo "$scriptname: Error: ${mac} doesn't match pattern \`ab:cd:ef:12:34:56'" >/dev/stderr
    exit 1
  fi

  ifconfig $interface hw ether ${mac%:*}:$number

unset number mac item
else
  echo "$scriptname: Error: HOSTNAME undefined" > /dev/stderr
fi

