1#!/bin/bash
2
3mac_config="/usr/share/mac-address/config.txt"
4dev_mac_path="/tmp/usb0_dev"
5host_mac_path="/tmp/usb0_host"
6
7check_usb_local_administered() {
8    is_enable="$(cat ${mac_config} | grep 'USBLAA')"
9    echo ${is_enable}
10}
11
12# Set the locally administered bit (the second least-significant
13# bit of the first octet) of the MAC address
14set_local_administered_bit() {
15    mac="$(cat $1)"
16    first_byte="${mac:0:2}"
17    first_byte="$((0x$first_byte|2))"
18    first_byte="$(printf "%02x\n" "$first_byte")"
19    mac="${first_byte}${mac:2}"
20    echo $mac
21}
22
23cd /sys/kernel/config/usb_gadget
24
25if [ ! -f "g1" ]; then
26    mkdir g1
27    cd g1
28
29    echo 0x1d6b > idVendor  # Linux foundation
30    echo 0x0104 > idProduct # Multifunction composite gadget
31    mkdir -p strings/0x409
32    echo "Linux" > strings/0x409/manufacturer
33    echo "Etherned/ECM gadget" > strings/0x409/product
34
35    mkdir -p configs/c.1
36    echo 100 > configs/c.1/MaxPower
37    mkdir -p configs/c.1/strings/0x409
38    echo "ECM" > configs/c.1/strings/0x409/configuration
39
40
41    if [[ $(check_usb_local_administered) == "USBLAA=true" ]]; then
42        dev_mac="$(set_local_administered_bit $dev_mac_path)"
43        host_mac="$(set_local_administered_bit $host_mac_path)"
44        echo $dev_mac > $dev_mac_path
45        echo $host_mac > $host_mac_path
46    fi
47
48    mkdir -p functions/ecm.usb0
49    cat $dev_mac_path > functions/ecm.usb0/dev_addr # write device mac address
50    cat $host_mac_path > functions/ecm.usb0/host_addr # write usb mac address
51
52    ln -s functions/ecm.usb0 configs/c.1
53
54    echo "$UDC" > UDC
55
56    rm $dev_mac_path
57    rm $host_mac_path
58
59fi
60
61exit 0
62