#!/bin/sh -e

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

# ignore device events
[ "$PRODUCT" ] || exit 0

# 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

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

  # kernels >= 2.6.10 have a built-in firmware loader
  case "$(uname -r)" in
    2.[789].*|2.6.[0-9][0-9]*)
      exit 0
      ;;
  esac
fi

if [ -z "$FIRMWARE_FILE" ]; then
  MODEM_REVISION=$(grep '^P: *Vendor=06b9 ProdID=4061 ' /proc/bus/usb/devices | 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

  FW='/usr/lib/hotplug/firmware/speedtch'
  REV=${MODEM_REVISION%.*}

  if   [ -e ${FW}-1.bin.$REV -a -e ${FW}-2.bin.$REV ]; then
    FIRMWARE_OPTIONS="-a ${FW}-1.bin.$REV -f ${FW}-2.bin.$REV"
  elif [ -e ${FW}-1.bin -a -e ${FW}-2.bin ]; then
    FIRMWARE_OPTIONS="-a ${FW}-1.bin -f ${FW}-2.bin"
  elif [ -e $FIRMWARE_FILE ]; then
    FIRMWARE_OPTIONS="-f $FIRMWARE_FILE"
  else
    echo "Cannot find the firmware files."
    exit 1
  fi
else
  FIRMWARE_OPTIONS="-f $FIRMWARE_FILE"
fi

##############################################################################
load_firmware() {
  if ! modem_run $MODEM_RUN_OPTIONS $FIRMWARE_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)
	( # do everything in the background
	load_firmware
	start_networking
	setup_remover
	) &
    ;;
esac

exit 0

