#!/bin/sh
#
# Configure the USB Gadget interface for diagnostic:
#
# * If mbimd is started then stop it.
# * Make sure the USB Gadget interface is disabled.
# * Only enable DIAG, USB serial, CDC NCM, and
#   USB audio (only configure Audio if ALSA is up).
# * Enable the USB interface, start adbd.
#
# Copyright (c) 2017 Valeo
#

# set USB_AUDIO to "yes" for proxying voice audio via USB
# otherwise the AFE proxy ports will be consumed by Linux userland which
# is only possible when the kernel USB driver does not access them.
# 2019-02-12@peiker/ol

USB_AUDIO="no"

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 [ "x$USB_AUDIO" = "xyes"  -a  -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.
if pidof mbimd > /dev/null
then
    start-stop-daemon --stop --quiet --name mbimd
fi

# 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
