#!/bin/sh
# Восстановление MAC-адреса по алгоритму sunxi-gmac из SID

SID="/sys/bus/nvmem/devices/sunxi-sid0/nvmem"
IFACE="end0"

if [ ! -r "$SID" ]; then
    echo "rd-restore-mac-legacy: SID not found" >&2
    exit 1
fi

MD5=$(dd if="$SID" bs=15 count=1 2>/dev/null | md5sum | cut -d' ' -f1)
if [ -z "$MD5" ] || [ ${#MD5} -lt 32 ]; then
    echo "rd-restore-mac-legacy: failed to compute MD5" >&2
    exit 1
fi

MAC=$(echo "$MD5" | awk '{
    mac = substr($1,1,2) ":" substr($1,5,2) ":" substr($1,9,2) ":" substr($1,13,2) ":" substr($1,17,2) ":" substr($1,21,2)
    print mac
}')

FIRST=$(echo "$MAC" | cut -d: -f1)
NEW_FIRST=$(printf "%02x" $(( (0x$FIRST & 0xFE) | 0x02 )))
MAC="$NEW_FIRST:$(echo $MAC | cut -d: -f2-)"

ip link set $IFACE address $MAC 2>/dev/null || {
    echo "rd-restore-mac-legacy: failed to set MAC $MAC on $IFACE" >&2
    exit 1
}

echo "rd-restore-mac-legacy: $IFACE MAC set to $MAC"
exit 0