#!/bin/sh
#
# Check if the USB Gadget interface is enabled.
#
# [Optional] For each function on the command line verify if it is
#            currently enabled.
#
# Examples of use:
#
# 1) Check if the USB gadget interface is enabled.
#
#    /etc/usb-g/usb-g-is-enabled
#
# 2) Check if the USB gadget audio function is enabled.
#
#    /etc/usb-g/usb-g-is-enabled audio
#
# 3) Check if the USB gadget ncm function is enabled.
#
#    /etc/usb-g/usb-g-is-enabled ncm
#
# 4) Check if the USB gadget rmnet function is enabled.
#
#    /etc/usb-g/usb-g-is-enabled rmnet
#
# 5) Check if the USB gadget diag function is enabled.
#
#    /etc/usb-g/usb-g-is-enabled diag
#
# 6) Check if the USB gadget serial function is enabled.
#
#    /etc/usb-g/usb-g-is-enabled serial
#
# 7) Check if multiple USB gadget functions are enabled.
#
#    /etc/usb-g/usb-g-is-enabled ncm serial audio
#
# Copyright (c) 2017 Valeo
#

INTERFACE=android0

# Check that the USB Gadget interface support is enabled in the kernel
if [ \! -e /sys/class/android_usb/$INTERFACE/enable ]
then
    exit 1
fi

# Check the USB gadget interface current status is enabled.
ENABLED=`cat /sys/class/android_usb/$INTERFACE/enable`
if [ "$ENABLED" != 1 ]
then
    exit 1
fi

# Check if each USB Gadget function listed on the command line
# is enabled.
FUNCTIONS=`sed 's/,/ /g' /sys/class/android_usb/$INTERFACE/functions`
for function_to_check in "$@"
do
    function_found=0
    for enabled_function in $FUNCTIONS
    do
        if [ "$function_to_check" = "$enabled_function" ]
        then
            function_found=1
        fi
    done
    if [ "$function_found" != 1 ]
    then
        exit 1
    fi
done

# If the script reached that point it means that all is enabled.
exit 0
