#!/bin/sh -e

PATH=/sbin:/bin:/usr/sbin:/usr/bin
export PATH

# if not set, a default is determined from the VC and VP values
OPEN_MODE="3"
# a PPP peer to call
PPPD_PEER=""
# an interface to start with ifup
NET_IF=""

# you can use this file to change the default configuration
[ -f /etc/default/xdslusb ] && . /etc/default/xdslusb

# no user-serviceable parts below this line
##############################################################################
case "$ACTION" in
    add)
    ;;
    *)
	exit 0
    ;;
esac

##############################################################################
if [ ! -f /proc/bus/usb/devices ]; then
    if ! mount -t usbdevfs none /proc/bus/usb 2> /dev/null; then
	echo "Cannot mount the USB device filesystem."
	exit 1
    fi
fi

##############################################################################
PRODUCT=$(echo $PRODUCT | sed -e 's#/# #g')
set $PRODUCT ''
VID=$1
PID=$2
RELEASE=$3

case "$VID/$PID" in
  506/*)
    LOADER_TYPE=3cp4218
    INIT_COMMAND="3cioctl 1"
  ;;
  6b9/a5a5|b05/6206)
    LOADER_TYPE=amedyn
    INIT_COMMAND="amioctl 1"
  ;;
  8e3/100|8e3/102|eb0/3457|572/*|675/200|1803/5510)
    LOADER_TYPE=cxacru
    INIT_COMMAND="cxioctl 1"
  ;;
  *)
    echo "The USB device $VID/$PID is not a known modem"
    exit 1
  ;;
esac

##############################################################################
# the module has to be removed before the firmware can be loaded
# this is very annoying! the module will be loaded by hotplug just before
# this script is run
DRIVER=$(lsmod | cut -d' ' -f1 | grep -E "^(cxacru|xdsluxb)(dbg)?[ \t]") \
	|| true
if [ "$DRIVER" ]; then
    rmmod $DRIVER
    sleep 1s
fi

# try to load the firmware
case "$LOADER_TYPE" in
  3cp4218)
    FIRMWARE_DIR=/usr/local/lib/3cp4218
    3cload 1 $FIRMWARE_DIR/ez-usb.bin
    sleep 5
    3cload 2 $FIRMWARE_DIR/3cinit.bin $FIRMWARE_DIR/3cmain.bin $OPEN_MODE
  ;;
  amedyn)
    amload
  ;;
  cxacru)
    cxload $OPEN_MODE
  ;;
esac

modprobe $DRIVER

# enable the connection
[ "$INIT_COMMAND" ] && $INIT_COMMAND

# install the script which will be executed at remove time
if [ "$INSTALL_REMOVER" -a "$REMOVER" ]; then
    printf "#!/bin/sh -e\n/usr/sbin/cxioctl 2\n" >> $REMOVER
    chmod +x $REMOVER
fi

# configure the network connection
if [ "$PPPD_PEER" ]; then
    sleep 5
    pppd call $PPPD_PEER
fi
if [ "$NET_IF" ]; then
    sleep 5
    ifup $NET_IF
fi

exit 0

