#!/bin/bash

t_mac=$1
ifname=eth1

function die(){
    local msg="$@"
    echo -e "$msg"
    exit 2
}

[ ${t_mac} ] || die "Usage: bash $0 6015922E0384\n6015922E0384 is an example of a MAC address"

count=$(echo ${t_mac} | wc -c)
[ ${count} -eq 13 ] || die "MAC address length error! The length of MAC(${t_mac}) is $((${count}-1))"

# n_mac=$(sudo ethtool -e ${ifname} offset 1 length 6 | grep 0x0001 | sed 's/0x0001:\t//g' | sed 's/^\s//g' | sed 's/\s$//g' | sed 's/\s/:/g')
# [ $? -eq 0 ] || die "Read the MAC address of ${ifname} Failed!"
# if [ "${n_mac}" != "60:15:92:2e:03:84" ];then
#     die "Current mac address is not 60:15:92:2e:03:84, no need to change"
# fi

addr=$(echo ${t_mac} | sed 's/.\{2\}/&:/g'| sed 's/:$//g')
IFS=":" read -a data <<< "$addr"

for i in {5..0}
do
    #echo "sudo ethtool -E ${ifname} magic 0x9500 length 0 offset $((i+1)) value "0x${data[$i]}""
    sudo ethtool -E ${ifname} magic 0x9500 length 1 offset $((i+1)) value "0x${data[$i]}"
    [ $? -eq 0 ] || die "Flash MAC address failed!"
done

echo -e "Mac address($t_mac) flashed \033[32msuccessfully!\033[0m"
echo "Please reboot device!"
