#!/bin/bash

ifname=eth1
base_url=http://101.133.146.9:8001

g_mac="0"
if [ $# -eq 1 ];then
    g_mac=$1
fi

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

function write_mac(){
    t_mac=$1
    [ ${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 "\e[31mFlash MAC address failed\e[0m"
    done

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

function check_mac(){
    if [ "${g_mac}" = "0" ];then
        t_mac=$(cat /sys/class/net/${ifname}/address | sed 's/://g' | awk '{print toupper($0)}')
    else
        t_mac=$g_mac
    fi

    n_mac_str=$(curl -X POST ${base_url}/mac/check -H "Content-Type: application/json" -d '{ "mac": "'${t_mac}'" }')
    echo 
    n_mac=$(echo $n_mac_str | python3 -c "import sys, json; data=json.load(sys.stdin); print(data['mac'])")
    if [ $? -eq 0 ];then
        if [ "${t_mac}" = "${n_mac}" ];then
            # echo "The MAC address is correct."
            echo -e "\e[32mThe MAC address is correct.\e[0m"
        else
            echo "Need to program ${n_mac}"
            write_mac ${n_mac}
            n_used=$(curl -X POST ${base_url}/mac/used -H "Content-Type: application/json" -d '{ "mac": "'${n_mac}'" }')
            echo 
            if [ "${n_used}" = "\"ok\"" ];then
                echo -e "\e[32mRecord successful\e[0m"
                exit 0
            else
                sleep 0.1
                n_used=$(curl -X POST ${base_url}/mac/used -H "Content-Type: application/json" -d '{ "mac": "'${n_mac}'" }')
                echo 
                if [ "${n_used}" = "\"ok\"" ];then
                    echo -e "\e[32mRecord successful\e[0m"
                    exit 0
                fi
            fi
        fi
    else
        echo "Please try again."
        exit 1
    fi
}

check_mac
