#!/bin/sh
#
# Configure the USB Gadget interface for development:
#
# * Disable the USB Gadget interface.
# * Enable DIAG, USB serial, RMNET, CDC NCM, and
#   USB audio (only configure Audio if ALSA is up).
# * Enable the USB Gadget interface.
# * Start adbd.
# * Start diagrebootapp.
# * Start mbimd.
#
# Copyright (c) 2017 Valeo
#

INTERFACE=android0
DELAY=0

enable_usb_gadget_functions () {
  IS_ENABLED=`cat /sys/class/android_usb/$INTERFACE/enable`
  ACTIVE_FUNCTIONS=`cat /sys/class/android_usb/$INTERFACE/functions`

  # Only re-configure the USB Gadget if required...
  if test -e /dev/snd/controlC0
  then
    if [ "$IS_ENABLED" = 1 -a "$ACTIVE_FUNCTIONS" = "diag,ffs,serial,ncm,audio" ]
    then
      return 0
    fi
  else
    if [ "$IS_ENABLED" = 1 -a "$ACTIVE_FUNCTIONS" = "diag,ffs,serial,ncm" ]
    then
      return 0
    fi
  fi

  # Make sure the USB gadget interface is disabled.
  echo 0 > /sys/class/android_usb/$INTERFACE/enable

  # Use the Qualcomm 0925 configuration, as it has good Windows driver support
  # which is useful during development.
  echo 9025 > /sys/class/android_usb/$INTERFACE/idProduct
  echo 05C6 > /sys/class/android_usb/$INTERFACE/idVendor

  # Configure the serial interface
  echo smd,tty > /sys/class/android_usb/$INTERFACE/f_serial/transports

  # Configure the DIAG interface
  echo diag > /sys/class/android_usb/android0/f_diag/clients

  # USB audio is only enabled if 
  if test -e /dev/snd/controlC0
  then
    echo diag,ffs,serial,ncm,audio > /sys/class/android_usb/$INTERFACE/functions
  else
    echo diag,ffs,serial,ncm > /sys/class/android_usb/$INTERFACE/functions
  fi

  # Set the serial number (ADB device ID)
  /etc/usb-g-config/usb-g-set-device-id

  # Enable remote wakeup
  echo 1 > /sys/class/android_usb/$INTERFACE/remote_wakeup
  sleep $DELAY

  # Enable the USB gadget interface
  echo 1 > /sys/class/android_usb/$INTERFACE/enable

}

#
# Main body of the script
#

# Stop the services that need to be disabled.

# Configure the USB Gadget functions
enable_usb_gadget_functions

# Start the ADB daemon
if ! pidof adbd > /dev/null
then
    start-stop-daemon --start --background --quiet --exec /sbin/adbd
fi

# Start the DIAG reboot daemon
if ! pidof diagrebootapp > /dev/null
then
    start-stop-daemon --start --background --quiet --exec /usr/bin/diagrebootapp
fi

# Start the MBIM daemon
if ! pidof mbimd > /dev/null
then
    rm -f /var/run/qbi_session_active
    start-stop-daemon --start --background --quiet --exec /usr/bin/mbimd
fi
