#!/bin/sh -e

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

# Add here the command line options for modem_run.
# -k will be automatically added later if needed.
MODEM_RUN_OPTIONS=""
# 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/speedtouch ] && . /etc/default/speedtouch

##############################################################################
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

# use -k if we are using the kernel space driver
if grep -q -E '^I:.*Driver=speedtch$' /proc/bus/usb/devices; then
  MODEM_RUN_OPTIONS="$MODEM_RUN_OPTIONS -k"
fi

if [ -z "$FIRMWARE_FILE" ]; then
  MODEM_REVISION=$(grep '^P: *Vendor=06b9 ProdID=4061 ' | sed -e 's/.*Rev= *([^ ]*)/\1/')

  case "$MODEM_REVISION" in
    0.00|2.00) # old stingray and purple frog
      FIRMWARE_FILE="/usr/local/lib/speedtouch/KQD6_3.012"
      ;;
    4.00) # new grey frog
      FIRMWARE_FILE="/usr/local/lib/speedtouch/ZZZL_3.012"
      ;;
    *)
      echo "Unknown modem revision $MODEM_REVISION"
      exit 1
      ;;
  esac
fi

if [ ! -e "$FIRMWARE_FILE" ]; then
  echo "Cannot find $FIRMWARE_FILE."
  exit 1
fi

MODEM_RUN_OPTIONS="$MODEM_RUN_OPTIONS -f $FIRMWARE_FILE"

##############################################################################
load_firmware() {
  if ! modem_run $MODEM_RUN_OPTIONS; then
    echo "Cannot initialize the modem."
    exit 1
  fi
  return 0
}

start_networking() {
  if [ "$PPPD_PEER" ]; then
    sleep 5
    pppd call $PPPD_PEER
  fi
  if [ "$NET_IF" ]; then
    sleep 5
    ifup $NET_IF
  fi
  return 0
}

# This is needed to work around a bug of modem_run not noticing that
# the modem has been unplugged. See #218795 for details.
setup_remover() {
  [ "$REMOVER" ] || return 0
  {
  echo "#!/bin/sh"
  [ "$PPPD_PEER" ] && printf "poff $PPPD_PEER\nsleep 5\n"
  echo "killall modem_run"
  } >> $REMOVER
  chmod +x $REMOVER
  return 0
}

##############################################################################
case "$ACTION" in
    add)
	load_firmware
	start_networking
	setup_remover
    ;;
esac

exit 0

