#! /bin/sh

. /etc/init.d/functions.sh
[ -f /etc/conf.d/mac ] && . /etc/conf.d/mac

DEFAULT_MAC="00:40:8C:CD:00:00"

begin "Determining MAC address"

if [ -n "$MAC" ]; then
	MAC=`echo $MAC | tr abcdef ABCDEF`
else
	MAC="$DEFAULT_MAC"
fi

if [ "$MAC" = "$DEFAULT_MAC" ]; then
	[ -x /bin/bootblocktool ] && serno=`bootblocktool -x SERNO` 
	if [ -z "$serno" ]; then
		warning "$0: Cannot determine serial number!"
		information "no serial number, using default MAC address: $MAC"
		set_led statusled ser_no_error \
			|| warning "$0: Could not set status-LED."
	else
		# Use serial number with colons added.
		MAC=`echo $serno | tr abcdef ABCDEF \
			| sed -e 's/\([0-9A-F]\{2\}\)/\1:/g;s/:$//'`
		information "using serial number as MAC address: $MAC"
	fi

	# Only write to the config-file if needed.
	if [ "$MAC" != "$DEFAULT_MAC" ] || [ ! -f /etc/conf.d/mac ]; then
		# Write the new address to the config-file.
		cat << EOT > /etc/conf.d/mac
# This file was automatically generated by "$0"
# to be used by the net-scripts if the conf-file of a net-script doesn't
# define MAC.
#
# Change MAC if you want a MAC address different than the serial number.

MAC="$MAC"
EOT
		information "MAC address saved: $MAC"
	fi
else
	information "using saved MAC address: $MAC"
fi

end $?

