ramips: add a script to fix up the broken mac address on the witi board
[openwrt/openwrt.git] / target / linux / ramips / base-files / sbin / fixup-mac-address
1 #!/bin/sh
2 . /lib/functions.sh
3 . /lib/functions/system.sh
4
5 partname=""
6 offset=""
7 NEW_MAC=
8 YES=
9
10 case "$(cat /tmp/sysinfo/board_name)" in
11 witi)
12 partname=factory
13 offset=$((0xe000))
14 ;;
15 *)
16 echo "Unsupported board"
17 exit 1
18 ;;
19 esac
20
21 while [ -n "$1" ]; do
22 case "$1" in
23 ??:??:??:??:??:??) NEW_MAC="$1";;
24 -y) YES=1;;
25 *)
26 cat <<EOF
27 Unknown option/argument '$1'
28 Usage: $0 [-y] [<macaddr>]
29 EOF
30 exit 1
31 ;;
32 esac
33 shift
34 done
35
36 ask_bool() {
37 local message="$1"
38 local default="$((! ${2:-0}))"
39 [ -n "$YES" ] && return 0
40 echo -n "$message "
41 read opt
42 case "$opt" in
43 y|Y) return 0;;
44 n|N) return 1;;
45 *) return $default;;
46 esac
47 }
48
49 convert_hex() {
50 hexdump -e '/1 "%02x "'
51 }
52
53 gen_mac() {
54 dd if=/dev/urandom bs=6 count=1 2>/dev/null
55 }
56
57 mac="$(mtd_get_mac_binary $partname $offset)"
58 case "$mac" in
59 00:00:00:00:00:00);;
60 ff:ff:ff:ff:ff:ff);;
61 *)
62 echo "Current MAC address: $mac"
63 ask_bool "Overwrite (y/N)?" 0 || exit
64 ;;
65 esac
66
67 if [ -n "$NEW_MAC" ]; then
68 set -- $(echo "$NEW_MAC" | sed 's,:, ,g')
69 else
70 set -- $(gen_mac | convert_hex)
71 set -- $(printf %02x $(( (0x$1 & 0xfe) | 0x02 ))) $2 $3 $4 $5 $6
72 fi
73 echo "New MAC address: $1:$2:$3:$4:$5:$6"
74 ask_bool "Write to EEPROM (y/N)?" || exit
75
76 part=$(find_mtd_part "$partname")
77 [ -n "$part" ] || exit
78 echo -ne "\x$1\x$2\x$3\x$4\x$5\x$6" | dd of=$part conv=notrunc bs=1 count=6 seek=$offset 2>/dev/null
79 echo "Done"