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

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

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

    # 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 printf "Not setting any MAC address!\\n" && 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
    OCOTP_CFG1_1=$(printf "%s" "$OCOTP_CFG1" | cut -c 1-2)
    OCOTP_CFG1_2=$(printf "%s" "$OCOTP_CFG1" | cut -c 3-4)
    OCOTP_CFG1_3=$(printf "%s" "$OCOTP_CFG1" | cut -c 5-6)
    mac="02:00:00:${OCOTP_CFG1_1}:${OCOTP_CFG1_2}:${OCOTP_CFG1_3}"
fi

printf "Setting new mac (%s) to interface (%s) ...\\n" "${mac}" "${interface}"

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

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

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

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

exit 0
