#!/bin/sh
#
# Configure the USB Gadget interface for production:
#
# * If adbd is started then stop it.
# * If mbimd is started then stop it.
# * Make sure the USB Gadget interface is disabled.
# * Only enable USB serial, CDC NCM, and USB audio (only configure Audio if ALSA is up).
# * Enable the USB interface, adbd is NOT started.
#
# 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,serial,ncm,audio" ]
    then
      return 0
    fi
  else
    if [ "$IS_ENABLED" = 1 -a "$ACTIVE_FUNCTIONS" = "diag,serial,ncm" ]
    then
      return 0
    fi
  fi

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

  # Assign new PID 9026 for current configuration instead of using the 9025 which
  # is for the development and maintance mode.
  echo 9026 > /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,serial,ncm,audio > /sys/class/android_usb/$INTERFACE/functions
  else
    echo diag,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 adbd > /dev/null
then
    start-stop-daemon --stop --quiet --name adbd
fi
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 DIAG reboot daemon
if ! pidof diagrebootapp > /dev/null
then
    start-stop-daemon --start --background --quiet --exec /usr/bin/diagrebootapp
fi

