#/bin/sh
# resetMACs.sh
#
# dispatcher for resetMAC.sh 
# - checks for matching hostnames and 
#   calls $resetMac.sh resets MAC address depending on HOSTNAME content
#
# created: 13-01-2010
# author: p.zumbruch, GSI
# modified: 13-01-2010

#debug - uncomment to debug
#set -xv

#predefines
	scriptname=resetMACs.sh
	myHostname=$(hostname)
	mylist='etrax042 etrax043 etrax044 etrax045 etrax046 etrax047 etrax048'
	HomeHadaq=/home/hadaq
	resetMACscript=${HomeHadaq}/EPICS/startupProcedures/resetMAC.sh
	interface=eth0
	
	unset myDebug;

#unset function
	unsets () 
	{
		unset myHostname mylist item resetMACscript
		unset scriptname HomeHadaq interface

		return 0;
	}

#usage function
usage()
{
	echo
	echo "$scriptname"
	echo "usage: $scriptname [options]" 
	echo 
	echo " dispatcher for resetMAC.sh,"
	echo "  checks for matching hostnames with a given list of hostname" 
	echo "  and calls resetMAC.sh, which resets their MAC according to the hostname"
	echo 
	echo "options:"
	echo "   -H hostname     : hostname"
	echo "                     [\`${myHostname}']"
	echo "   -s scriptname   : resetMACscript name (absolute path) "
	echo "                     [\`${resetMACscript}']"
	echo "   -e interface    : uses ethernet interface"
	echo "                     [\`$interface']"
	echo "   -l list         : quoted space separated list of hostnames, whose MACs are to be reset"
	echo "                     [\`\"$mylist\"']"
	echo "   -D              : just echos command instead of executing [$([ -z "${myDebug}" ] && echo OFF || echo ON)]"
	echo "   -d              : debug mode sets set -xv"
	echo "   -h              : this help"  
	echo
}

#eval options
	while getopts dhe:l:s:DH: arg
	do
		case $arg in
			\? | h )usage ; 
				unsets;
				exit 0;
				shift ;; 
			H ) 	myHostname=$OPTARG;
				shift 2;;
			e ) 	interface=$OPTARG;
				shift 2;;
			l ) 	mylist=$OPTARG;
				shift 2;;
			s ) 	resetMACscript=$OPTARG;
				shift 2;;
			d ) 	set -xv 
				shift;;
			D ) 	myDebug=echo 
				shift;;
		esac
	done

#checks, directories and permissions ...
	# hostname
	if [ -z "$myHostname" ]
	then
		echo "$scriptname: hostname not available ... exiting" 1>&2
		unsets
		exit 1;
	fi
        # interface
	if [ -z "$interface" ]
	then
		echo "$scriptname: interface not set ... exiting" 1>&2
		unsets
		exit 1;
	fi
        # resetMAC script
	if [ ! -x "${resetMACscript}" ]
	then
		echo "$scriptname: reset MAC Script: \`${resetMACscript}' is not executable or available ... exiting" 1>&2
		unsets
		exit 1;
	fi

#execute
	for item in $mylist
	do 
		if [ "$item" = "$myHostname" ]
		then
			${myDebug} ${resetMACscript} -e ${interface} 
		break;
		fi
	done

	unsets 

exit 0

