#!/bin/bash
#
# MAC address changer
# -------------------
# Version: 0.1
#
# by d1s4st3r
# http://xoomer.alice.it/mental_insomnia/


function randomMAC()
{
	DIGITS="0123456789ABCDEF"
	LENGTH="12"

	while [ "${n:=1}" -le "$LENGTH" ]
	do
		PASS="$PASS${DIGITS:$(($RANDOM%${#DIGITS})):1}"
		if [ $(($n%2)) -eq 0 ] && [ $n -lt $LENGTH ]; then
			PASS="$PASS:"
		fi
	let n+=1
	done

	echo "$PASS"
}

if [ ! "`id -u`" = "0" ]; then
	echo "Sorry, only root may run this script."
	exit 1
fi

IF_NUMBER=`ifconfig -a | grep Ethernet | wc -l`

I=0
for ITEM in `ifconfig -a | grep Ethernet | awk '{print $1}'`; do
	IF_DEV[$I]=$ITEM;
	let "I += 1"
done

I=0
for ITEM in `ifconfig -a | grep Ethernet | awk '{print $5}'`; do
	IF_OLDMAC[$I]=$ITEM;
	let "I += 1"
done

clear
echo "+----------------------------------------------+"
echo "|          MAC address changer - v0.1          |"
echo "|                  by d1s4st3r                 |"
echo "+----------------------------------------------+"
echo ""

I=0
echo -e "\tINTERFACE\tMAC ADDRESS\t\tACTIVE"
echo -e "\t---------\t-----------\t\t------"
while [ "$I" -lt "$IF_NUMBER" ]; do
	TMP=`ifconfig -s | grep ${IF_DEV[$I]} | awk '{print $1}'`
	if [ "$TMP" == "" ]; then
		ACT="NO"
	else
		ACT="YES"
	fi
	echo -e "$I)\t${IF_DEV[$I]}\t\t${IF_OLDMAC[$I]}\t$ACT"
	let "I += 1"
done
echo ""
echo -n "Please choose network interface (or press q to quit): "
read IF_NUM

if [ "$IF_NUM" = "q" ]; then
	exit
elif ! [ $IF_NUM -eq $IF_NUM 2> /dev/null ] || [ "$IF_NUM" == "" ] || [ "$IF_NUM" -ge "$I" ]; then
	echo "Not a valid interface!"
	exit
else
	echo ""
	echo "How to set new MAC address for interface ${IF_DEV[$IF_NUM]}?"
	echo ""
	echo "1) Manually "
	echo "2) Randomly"

	echo ""
	echo -n "Number: "
	read OPT

	case $OPT in
	1)
		echo -n "New MAC address: "
		read IF_NEWMAC
		# check right XX:XX:XX:XX:XX:XX MAC address format with a regexp
		ifconfig ${IF_DEV[$IF_NUM]} hw ether $IF_NEWMAC &> /dev/null
		if [ "$?" -eq "0" ]
		then
			echo "New MAC address $IF_NEWMAC succesfully set to interface ${IF_DEV[$IF_NUM]}."
		else
			echo "Error while setting new MAC address $IF_NEWMAC to interface ${IF_DEV[$IF_NUM]}."
		fi
		;;
	2)
		IF_NEWMAC=`randomMAC`
		ifconfig ${IF_DEV[$IF_NUM]} hw ether $IF_NEWMAC &> /dev/null
		if [ "$?" -eq "0" ]
		then
			echo "New MAC address $IF_NEWMAC succesfully set to interface ${IF_DEV[$IF_NUM]}."
		else
			echo "Error while setting new MAC address $IF_NEWMAC to interface ${IF_DEV[$IF_NUM]}."
		fi
		;;
	*)
		echo "Invalid option!"
		;;
	esac
fi


# TODO
# ----
#
# When some error occurs, loop again to the main menu instead of getting out of the script.
# Switch/case options should be grouped into one function.
# More functions, more procedures!

