#!/bin/sh

# This script is written for busybox ash, which is enabled on X1.
# Comparisons may not work with other shells.

interface="eth0"
mac=""
success=true

print_usage(){
    echo "Usage: set-mac-to-if [interface] <MAC>|auto"
    echo "  interface defaults to eth0"
    echo "  Remember, the first octet needs to be even for unicast addresses"
    echo "  If instead of <MAC> the literal 'auto' is given, the first half"
    echo "  is 02:00:00: and the last half are the first six digits (lsb first)"
    echo "  the i.MX6 register 'OTP Bank0 Word2'."
}

case $# in
        1)      mac="$1";;
        2)      interface="$1"
                mac="$2";;
        *)      echo "Wrong number of arguments!"
                print_usage
                exit 1;;
esac

if [ "${mac}" == "auto" ]
then
    echo "Automatic mode. Using MAC from serial number."

    # The number used for generating the mac is the first 6 digits of
    # the i.MX6 OTP Bank0 Word 1 (OCOTP_CFG1).
    # Note that leading 0 (zeros) after 0x are omitted by cat! 0x01 will display as 0x1.
    OCOTP_CFG1=$(cat /sys/fsl_otp/HW_OCOTP_CFG1 | cut -d 'x' -f2)
    # Exit if reading register failed
    if [ -z "${OCOTP_CFG1}" ]; then echo "Not setting any MAC address!  " && exit 1; fi
    # cat omits leading zeros. So fill them up if missing.
    while [ ${#OCOTP_CFG1} -lt 8 ]
    do
        OCOTP_CFG1="0${OCOTP_CFG1}"
    done
    mac="02:00:00:${OCOTP_CFG1:0:2}:${OCOTP_CFG1:2:2}:${OCOTP_CFG1:4:2}"
else
    exit 0
    # Has anyone any reason for the below stuff?
    # As it leads too issues at least for android
    # devices do not execute it.
    # The address _is_ set. So do not fumble around
    # here as long as it is not required.
fi

echo "Setting new mac (${mac}) to interface (${interface}) ..."

ip link set dev ${interface} down
if [ $? != 0 ]
then
    echo "Failed to bring interface ${interface} down!"
    exit 1
fi

ip link set dev ${interface} address ${mac}
if [ $? != 0 ]
then
    echo "Failed to set mac address ${mac} to interface ${interface}!"
    print_usage
    success=false
fi

ip link set dev ${interface} up
if [ $? != 0 ]
then
    echo "Failed to bring interface ${interface} back up"!
    exit 1
fi

if [ "$success" = true ]
then
    echo "Persisting mac address ..."
    echo "${mac}" > /opt/extparam/mac_address_0
    echo "Done. Device should soon be up again."
fi

exit 0
