#!/bin/sh

# Copyright (C) 2006 OpenWrt.org

PROTO=$(uci -q get network.wan.proto)
BACKUP3G=$(uci -q get network.3gwan.backup)
UP3GWAN=$(uci -q -P /var/state get network.3gwan.up)

product=$(echo $PRODUCT|sed "s/\// /g")
ven_num=$(echo $product|awk '{print $1}')
pro_num=$(echo $product|awk '{print $2}')
new_product=$(printf "%4s" "$ven_num"|sed "s/ /0/g")"/"$(printf "%4s" "$pro_num"|sed "s/ /0/g")"/0"
# Try to make information as : vendor/product/0. vendor/product are both 4 bytes.
PRODUCT=$new_product

case "$ACTION" in
	remove)		
		# remove Sony Ericson MD300 so setup configuration back to default
		if [ ${PRODUCT} == "fce/d0cf/0" ]; then
			uci -q set network.wan.init_string2='ATE0V1X1&D2&C1S0=0'
			uci -q set network.3gwan.init_string2='ATE0V1X1&D2&C1S0=0'
			uci commit network
		fi
		
		# removed device is 3g device
		INUSE=$(uci -q -P /var/state get network.3gdev)
		[ ${PRODUCT} == "$INUSE" ] && {
			logger "USB 3G device $PRODUCT removed!!!!"
			if [ "$PROTO" = "3g" ]; then
				ifdown wan
				killall pppd
			fi
			if [ "$UP3GWAN" == 1 ]; then
				uci -q -P /var/state revert network.3gwan.up
			fi
			uci -q -P /var/state revert network.3gif
			uci -q -P /var/state set network.3gif="ttyUSB0"
			uci -q -P /var/state revert network.3gdev
			exit 1
		}
		
		#unknown 3G device case. 
		if [ "$INUSE" != "" ]; then
			DEV=$(uci -q get network.3gif)
	  		if [ "$DEV" != "" ]; then
				TEST=$(gcom -d $DEV sig | grep "Can't open device")
			else
				TEST=$(gcom | grep "Unable to locate default")
			fi
	
			if [ "$TEST" != "" ]; then
				logger "USB 3G device $PRODUCT removed!!!!"
				if [ "$PROTO" = "3g" ]; then 
					ifdown wan
					killall pppd
				fi
				if [ "$UP3GWAN" == 1 ]; then
					uci -q -P /var/state revert network.3gwan.up
				fi
				uci -q -P /var/state revert network.3gif
				uci -q -P /var/state set network.3gif="ttyUSB0"
				uci -q -P /var/state revert network.3gdev
			fi
		fi	
		;;
	add)
		#now we always set mode switch to all USB device.
		draytek_hsdpa ${PRODUCT}
		
		#check if we need to lock device.
		INUSE=$(uci -q -P /var/state get network.3gdev)
		if [ "$INUSE" == "" ]; then
			DEV=$(uci -q -P /var/state get network.3gif)
			if [ "$DEV" != "" ]; then
				TEST=$(gcom -d $DEV sig | grep "Can't open device")
			else
				TEST=$(gcom | grep "Unable to locate default")
			fi
	                
			if [ "$TEST" != "" ]; then
				#logger "3G device not exist........."
				exit 1
			fi
			
			uci -q -P /var/state set network.3gdev=${PRODUCT}
			logger "USB 3G device $PRODUCT connected!!!!"
			logger "SUCCESS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
			#if protocol is 3g, try 3g wan up.
			if [ "$PROTO" = "3g" ]; then
				#copy usb interface to wan.device
				uci -q set network.wan.device=${DEV}
				uci commit network
				ifup wan
			fi
			#if 3G backup enable, lock device
			if [ "$BACKUP3G" = "1" ]; then
				#copy usb interface to 3gwan.device
				uci -q set network.3gwan.device=${DEV}
				uci commit network
			fi
		fi
esac

