#! /bin/sh
#
# Startup script for USBnet (networking, instead of USB Mass Storage behaviour)
# Author: Kyller Gorgonio (based on Michael Mlivoncic usbnet script)

NAME=usbnet
DESC="USB Networking for Nokia Internet Tablets"
INITFILE=/etc/init.d/$NAME
G_STORAGE=/mnt/initfs/lib/modules/`uname -r`/g_file_storage.ko
G_STORAGE_OPTS="stall=0 luns=2 removable"

# Start RNDIS/Ethernet networking device
run_insmod() {
	/sbin/insmod $1 $2
	if [ $? != 0 ] ; then
		echo "$NAME: insmod exited with failure" >> /tmp/usbnet
		return 1
	fi
	return 0
}

# Delay to let kernel do it's magic
yield() {
	sleep 1
}

# Unload any existing gadget drivers
unload() {
	rmmod $1
	if [ $? -ne 0 ]; then
		echo "$1: rmmod exited with failure" >> /tmp/usbnet
	fi
	yield
}

fremantle_switch_to_usb_network() {
    /sbin/ifup usb0
}

fremantle_switch_to_file_storage() {
    # File storage is not working
    /sbin/ifdown usb0
}

fremantle_check_g_ether_status() {
    ifconfig | grep usb0
    exit $?
}

switch_to_host () {
#	# remove g_file_storage module
#	if grep -q "g_file_storage" /proc/modules ; then
#		unload g_file_storage
#	fi
	
    echo host > /sys/devices/platform/musb_hdrc/mode
}

switch_to_otg () {
    echo otg > /sys/devices/platform/musb_hdrc/mode    
}

case "$1" in
start)
	echo "switching to USB network mode" >> /tmp/usbnet
	switch_to_otg
    fremantle_switch_to_usb_network
	;;
stop)
	echo "switching back to USB Mass Storage mode" >> /tmp/usbnet
	switch_to_otg
    fremantle_switch_to_file_storage
	;;
status)
	echo "checking usbnet status" > /tmp/usbnet
    fremantle_check_g_ether_status
	;;
host)
    echo "changing usb to host mode" >> /tmp/usbnet
    switch_to_otg
    switch_to_host
    ;;
otg)
    echo "changing usb to otg mode" >> /tmp/usbnet
    switch_to_otg
    ;;
*)
	echo "usbnet syntax error" >> /tmp/usbnet
	printf "Usage: $INITFILE {start|stop|status}\n" >&2
	exit 1
	;;
esac

exit 0

