#!/bin/bash

# Create gadget
cd /sys/kernel/config/usb_gadget
mkdir -vp g1
cd g1

echo "0x1d6b" > idVendor  # Linux Foundation
echo "0x0104" > idProduct # Multifunction Composite Gadget
echo "0x0001" > bcdDevice # v0.1.0
echo "0x0200" > bcdUSB    # USB 2.0

mkdir strings/0x409       # English strings
echo "CentOS"   > strings/0x409/manufacturer
echo "PiGadget" > strings/0x409/product
echo "1"        > strings/0x409/serialnumber

# Configure composite device
echo "0xEF" > bDeviceClass
echo "0x02" > bDeviceSubClass
echo "0x01" > bDeviceProtocol

# Make it work with windows
echo "1" > os_desc/use
echo "0xcd" > os_desc/b_vendor_code
echo "MSFT100" > os_desc/qw_sign

# Create Ethernet Endpoint (CDC NCM)
mkdir -vp functions/ncm.usb0
cat functions/ncm.usb0/host_addr

# Make the MAC address stable
echo 3e:50:66:69:12:a3 > functions/ncm.usb0/host_addr

# Set compatible id so that Windows 10 can match this function to NCM driver more easily.
echo "WINNCM" > functions/ncm.usb0/os_desc/interface.ncm/compatible_id

## Create serial endpoint
#mkdir -vp functions/acm.usb0

# Create configuration 1
mkdir -vp configs/c.1
mkdir configs/c.1/strings/0x409
echo "Gadget Config 1" > configs/c.1/strings/0x409/configuration

ln -s functions/ncm.usb0 configs/c.1 # Use ncm in configuration 1
#ln -s functions/acm.usb0 configs/c.1 # Use serial in configuration 1
ln -s configs/c.1 os_desc/c.1

# Find the UDC name:
NAME=$( ls /sys/class/udc/ )

udevadm settle

# Enable the gadget:
echo ${NAME} > /sys/kernel/config/usb_gadget/g1/UDC

# Enable the USB network
ifconfig usb0 up
ifconfig usb0 192.168.42.15
ip route add default via 192.168.42.1
echo "nameserver 192.168.42.1" > /etc/resolv.conf
