#!/bin/sh

set -e

UDC="${ADBD_GADGET_UDC}"
if [ "${UDC}" ] && [ ! -e "/sys/class/udc/${UDC}" ]
then
    echo "ERROR: /sys/class/udc/${UDC} doesn't exist!" >&2
    echo "Please check the contents of ADBD_GADGET_UDC" >&2
    exit 1
fi

if [ -z "${UDC}" ] && [ -d "/sys/class/udc" ]
then
    UDC="$(ls /sys/class/udc | head -1)"
fi

# Check we have a USB Device Controller available
[ "${UDC}" ] || exit 0

CONFIGFS_DIR="/sys/kernel/config/usb_gadget/g1"

setup()
{
    # Create USB gadget config
    # Note: vendor ID 0x18d1 is Google's ID, this allows the gadget to be
    # properly matched by the udev rules shipped by the Android SDK
    mkdir -p ${CONFIGFS_DIR}/configs/c.1
    cd ${CONFIGFS_DIR}

    mkdir -p strings/0x409
    mkdir -p configs/c.1/strings/0x409

    echo 0x0100 > idProduct
    echo 0x18D1 > idVendor

    echo "Debian" > strings/0x409/manufacturer
    echo "ADB device" > strings/0x409/product
    # Derive the serial number from the machine-id so it's unique
    echo "$(sha256sum < /etc/machine-id | cut -d' ' -f1)" > strings/0x409/serialnumber

    echo "ADB Configuration" > configs/c.1/strings/0x409/configuration
    echo 120 > configs/c.1/MaxPower

    # Add ADB config using FunctionFS
    mkdir -p functions/ffs.adb
    ln -s functions/ffs.adb configs/c.1

    # Mount FunctionFS where adbd expects it
    mkdir -p /dev/usb-ffs/adb
    mount -t functionfs adb /dev/usb-ffs/adb
}

activate()
{
    echo "${UDC}" > ${CONFIGFS_DIR}/UDC
}

reset() {
    umount /dev/usb-ffs/adb
    rmdir /dev/usb-ffs/adb
    rm ${CONFIGFS_DIR}/configs/c.1/ffs.adb
    rmdir ${CONFIGFS_DIR}/configs/c.1/strings/0x409/
    rmdir ${CONFIGFS_DIR}/configs/c.1/
    rmdir ${CONFIGFS_DIR}/functions/ffs.adb
    rmdir ${CONFIGFS_DIR}/strings/0x409/
    rmdir ${CONFIGFS_DIR}

}

case "$1" in
    "setup") setup ;;
    "activate") activate ;;
    "reset") reset ;;
    *) echo "Usage: $0 [setup|activate|reset]"; exit 1 ;;
esac
