#!/bin/bash
# Jetson Nano|TX1 UMS Gadget script
# Author: Azkali Manad <a.ffcc7@gmail.com>
set -e

emmc_enabled() {
        if [[ "$(cat /proc/device-tree/sdhci@700b0200/status)" != "okay" ]]; then
                echo "eMMC is disabled."; return 1
        fi
}

unmount() {
        if [[ ! -e "${DEVICE}" ]]; then exit 1;
        elif [[ $(mount | grep -qs ${1}) ]]; then
                echo "Unmounting: ${1}."
                umount ${1}
                [[ $? = "32" ]] && exit 1
        fi
}

# trap "Error on line $(caller)" ERR EXIT

export PARTITION="$2" MMC_INDEX="0"
if [ "$UDEV" = "true" ]; then
        echo "Triggered from udev"
        export DEVICE="/dev/mmcblk${MMC_INDEX}p1"
        unmount ${DEVICE}
else
        [[ "$EUID" -ne 0 ]] && exit 1

        if [[ -z "$1" ]]; then echo "Mounting the whole SD Card.";
        elif [[ "$1" = "1" ]]; then emmc_enabled || export MMC_INDEX="1"; fi

        export DEVICE="/dev/mmcblk${MMC_INDEX}"
        if [[ -n "${PARTITION}" ]]; then
                export DEVICE="/dev/mmcblk${MMC_INDEX}p${PARTITION}"
                unmount ${DEVICE}
        else umount "${DEVICE}p"?*; fi
fi

cd /sys/kernel/config/usb_gadget/l4t/
if [[ ! -L "configs/c.1/mass_storage.0" || ! -d "functions/mass_storage.0/" ]]; then
        mkdir -p functions/mass_storage.0/lun.0/
        echo "${DEVICE}" > functions/mass_storage.0/lun.0/file
        echo 0 > functions/mass_storage.0/stall
        echo 0 > functions/mass_storage.0/lun.0/cdrom
        echo 0 > functions/mass_storage.0/lun.0/nofua
        echo 1 > functions/mass_storage.0/lun.0/removable
        echo "SWITCHROOT" > functions/mass_storage.0/lun.0/inquiry_string
        ln -s functions/mass_storage.0 configs/c.1

        # Finally reset UDC
        [ -s UDC ] && echo "" > UDC
        ls /sys/class/udc/ > UDC
else
        unlink configs/c.1/mass_storage.0
        rmdir functions/mass_storage.0/
        [ -s UDC ] && echo "" > UDC
fi
