#!/bin/bash

set -e

if test $# != 1; then
    die "Error: Usage $(basename $0) MAC"
fi

if echo "$1" | grep -q -i -e '^\([0-9a-f]\{2\}:\)\{5\}\([0-9a-f]\{2\}\)$'; then
    MAC=$1
else
    die "Error: invalid MAC format: $1"
fi

byte2=${MAC:1:1}
byte2=$(printf %x $(( (0x$byte2  + (0x$byte2 % 2 ? 1 : 0)) % 16 )))
MAC=$(echo $MAC |sed -e 's/^\(.\)./\1'$byte2'/')
echo "set MAC to $MAC"
sed -r -e 's/^(mac_addr=.*?:)\s.*/\1  '$MAC'/' -i /factory/wifi_init_cfg.conf
sed -r -e 's/^(mac_addr=.*?:)\s.*/\1  '$MAC'/' -i $(readlink -f /etc/firmware/mrvl/wifi_init_cfg.conf) || true
touch /factory/wifi-mac-written
